简体   繁体   中英

listen component for change @Input() value in angular 8

hi i have this component . in this component i have @Input() userId: number[] = []; for send list of id to this component .

i use this component in other component , for example i use it in the news component :

<kt-user-post-list-select [userId]="noWriterIdList" (selectedUserId)="getSelectionUserList($event)">
</kt-user-post-list-select>

when i send a request to server for add news it return to me list of id : [1,2,3] and then i must send that ids to the kt-user-post-list-select with this [userId]="noWriterIdList" , But i have Problem : i need when pass the list to this component it track the changes and execute this function :

    validateUSerIsWriter(ids: number[]): void {
    for (let id = 0; id < ids.length; id++) {
        let user = this.users.find(x => x.userId = id);
        if (user != null) {
            user.isDeleted = true;

        }
    }
}

but it dosent any work .

how can i solve this problem ???

There are 2 ways

  1. Use ngOnChanges hook inside kt-user-post-list-select component. So you can listen for new Ids and execute the function validateUSerIsWriter . But remember, this comes with a cost of compromising performance.

  2. Use Subject to subscribe for the newIds, and execute the function validateUSerIsWriter . In this case you don't need @Input decorator. Please refer this simple example https://stackblitz.com/edit/angular-subject-observable

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM