【问题标题】:Updating ngFor when Input value changes当输入值改变时更新 ngFor
【发布时间】:2017-10-22 20:53:56
【问题描述】:

我正在尝试更好地了解 Angular 2。我从端点接收人员列表并定期更改列表。人员组件:

@Component({
   selector: 'people-display',
   template: <ol class="people-list">
                <li *ngFor="let person of people">
                   <attendees [people]="peopleValue"></attendees>
                </li>
             </ol>
})
export class PeopleComponent implements OnChanges {
   @Input() people: string[];
}

与会者组件:

@Component({
  selector: 'attendees',
  templateUrl: '<span>{{attendees}}</span>',
})
export class AttendeesComponent implements OnInit {
  constructor() { }
  ngOnInit() {}
}

我一直在寻找一种在输入值更改时自动更新我的模板的方法。我还没有找到这样做的方法。我考虑过做一个 setTimout,但必须有更有效的方法。有人可以帮助我或指出我正确的方向吗?我需要 ngFor 动态更新。

【问题讨论】:

    标签: angular angular2-template ngfor


    【解决方案1】:

    问题是如何将people 传递给组件。

    假设你的组件是my-people,那么你应该通过people如下

    <my-people [people]="peopleValue" .... ></my-people>
    

    【讨论】:

    • 我有这个,我收到一个错误。错误表明 people 不是 li &lt;li *ngFor="let person of people" [people]="peopleValue"&gt;{{person}}&lt;/li&gt; 的已知属性
    • [people]="peopleValue" is not on the
    • `的绑定。它去你要使用自定义组件的地方
    【解决方案2】:

    您不必手动执行任何操作来跟踪更改,angular2 框架会自动执行此操作,确保您将人员作为输入传递给您的子组件,

    假设 mycomponent 是您的子组件,people 是输入

    <mycomponent [people]="peopleValue" .... ></mycomponent>
    

    【讨论】:

    • 似曾相识!
    • @AmrElAdawy 是的,我没注意到你的回答,抱歉
    • 我有这个,我收到一个错误。错误表明 people 不是 li &lt;li *ngFor="let person of people" [people]="peopleValue"&gt;{{person}}&lt;/li&gt; 的已知属性
    【解决方案3】:

    为了您的目的,Angular 为您提供two way binding,其中对模型的任何进一步更改都会自动反映到模板中,反之亦然。

    例子:

    列表组件

    @Component({
        selector: 'my-comp',
        template: `<ul>
                        <li *ngFor="let item of people">{{item}}</li>
                   </ul>`
    })
    
    export class MyComp {
        @Input() people: string[];
    }
    

    用法

    @Component({
        selector: 'main-comp',
        template: '<my-comp [people]="list"></my-comp>'
    })
    
    
    export class MainComp {
        private list: string[];
    
        ngOnInit() {
            this.list= ['male', 'female'];
        }
    }
    

    【讨论】:

    • 不,不要那样做。为了减少代码耦合,增加模块化和代码复用性,总是尽可能的拆分代码。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签