Issue
let say I have Button
component like bellow
button.component.ts
import { CommonModule } from '@angular/common'
import { Component, Input } from '@angular/core'
@Component({
selector: 'app-button',
standalone: true,
imports: [CommonModule],
templateUrl: './button.component.html',
styleUrl: './button.component.scss'
})
export class ButtonComponent {
@Input() type?: string
@Input() click?: () => any
}
button.component.html
<button (click)="click?.()" [type]="type || 'submit'" class="button">
<ng-content></ng-content>
</button>
Then I use the button in another component
home.component.ts
import { CommonModule, } from '@angular/common'
import { Component } from '@angular/core'
import { FormBuilder, ReactiveFormsModule } from '@angular/forms'
import { ButtonComponent } from '../shared/button/button.component'
import { ISignIn } from './home.interface'
import { HomeService } from './home.service'
@Component({
selector: 'app-home',
standalone: true,
imports: [CommonModule, ButtonComponent, ReactiveFormsModule],
providers: [HomeService],
templateUrl: './home.component.html',
styleUrl: './home.component.scss'
})
export class HomeComponent {
constructor(private formBuilder: FormBuilder) { }
form = this.formBuilder.group<ISignIn>({
email: '',
password: ''
})
signIn() {
console.log(this.formBuilder) // got undefined
const value = this.form.value
console.log(value)
}
}
home.component.html
<form [formGroup]="form">
<input type="text" placeholder="Email" formControlName="email" />
<input type="password" placeholder="Password" formControlName="password" />
<app-button [click]="signIn">Login</app-button>
</form>
Solution
It is important to understand that at runtime, your function signIn
looses its context. When the app runs in the browser, the this
context will be lost, since in that situation, the global context takes place. In order to fix this, you will have to pass into your child component signIn.bind(this)
, not only signIn
.
A more Angular approach would be:
- define an @Output property inside your child component (which could be subtype of
Observable
or simply anEventEmitter<T>
) - this property must
emit
a value every time you want your parent component to react to that event
Answered By - Francesco Moro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.