简体   繁体   English

侦听组件以更改角度 8 中的 @Input() 值

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

hi i have this component .嗨,我有这个组件。 in this component i have @Input() userId: number[] = [];在这个组件中,我有@Input() userId: number[] = []; for send list of id to this component .用于将 id 列表发送到此组件。

i use this component in other component , for example i use it in the news component :我在其他组件中使用这个组件,例如我在news组件中使用它:

<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 :当我向服务器发送添加新闻的请求时,它返回给我的 id 列表: [1,2,3]然后我必须将该 id 发送到带有此[userId]="noWriterIdList"kt-user-post-list-select [userId]="noWriterIdList"但我有问题:我需要将列表传递给该组件时,它会跟踪更改并执行此功能:

    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有2种方式

  1. Use ngOnChanges hook inside kt-user-post-list-select component.kt-user-post-list-select组件中使用ngOnChanges钩子。 So you can listen for new Ids and execute the function validateUSerIsWriter .所以你可以监听新的 Id 并执行函数validateUSerIsWriter But remember, this comes with a cost of compromising performance.但请记住,这会导致性能下降。

  2. Use Subject to subscribe for the newIds, and execute the function validateUSerIsWriter .使用Subject订阅 newIds,并执行函数validateUSerIsWriter In this case you don't need @Input decorator.在这种情况下,您不需要@Input装饰器。 Please refer this simple example https://stackblitz.com/edit/angular-subject-observable请参考这个简单的例子https://stackblitz.com/edit/angular-subject-observable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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