首页 文章

输入值更改时更新ngFor

提问于
浏览
0

我正在尝试更好地理解Angular 2.我从 endpoints 接收人员列表,并定期更改列表 . 人物成分:

@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 .

3 回答

  • 0

    问题是如何将 people 传递给您的组件 .

    假设您的组件是 my-people ,那么您应该传递 people ,如下所示

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

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

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

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

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

    例:

    List Component

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

    Usage

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

相关问题