I am trying to implement a custom two way binding between two of my components.
I did read about the naming convention saying that you have to define a @Input()
like " test
" and then define a @Output()
named " testChange
".
I couldn't find anything about whether this is still up-to-date or not and I can't get my binding to work.
Some code within parentComponent:
<my-comp [(userGroupIds)]="userGroups"></my-comp>
MyComponent (child):
export class MyComponent implements OnInit, OnDestroy{
@Input() userGroupIds: number[];
@Output() userGroupIdsChange = new EventEmitter<number[]>();
updateValues(){
//here I am iterating through the rows of a table within my component
this.userGroupIds = this.tableRows.map(item => {return item['id']});
this.userGroupdIdsChange.emit(this.userGroupIds);
}
}
parentComponent:
export class parentComponent implements OnInit, OnChanges, OnDestry{
userGroups: number[];
constructor(){
this.userGroups = [];
}
ngOnChanges(changes: SimpleChanges){
if(changes['userGroups']){
// this is never show, ngOnChanges doesn't get fired;
console.log(this.userGroups);
}
}
}
Is there something I am missing? Did the Angular-Team change anything?
Afaik the binding does something like
[userGroupsIds]="userGroups" (userGroupsIdsChange)="userGroupIds=$event"
So I tried setting this myself, but no update either. Only thing that work was passing a function to the eventEmitter.
Your binding works like a charm, it does not trigger the ngOnchanges
method, which is the expected behavior.
from the Angular docs :
OnChanges
Lifecycle hook that is called when any data-bound property of a directive changes.
as userGroups
is not an @Input()
it cannot be a "data-bound property" , its value changing internally will not run the ngOnChanges
hook.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.