简体   繁体   English

使用setter方法更改变量时,Angular 2不绑定

[英]Angular 2 doesn't bind when change a variable using setter method

I have the following AngularJS 2 cide and my problem is that when calling the setter method setCourse the new data "java" doesn't reflect to the UI. 我有以下AngularJS 2实例,我的问题是,当调用setter方法setCourse ,新数据“ java”无法反映到UI。 So it's supposed to show "java" instead of "x,y,z" but it doesn't. 因此,应该显示“ java”而不是“ x,y,z”,但不会显示。

import {Component} from 'angular2/core'

@Component({selector:'course',
template: `
<ul> <li *ngFor="#x of courses">  {{ x }}</li> </ul>`
})
export class CourseComponent {
private courses: string[] = ['x ' , 'y ' , 'z'];

public setCourse(courses:string[]){
    this.courses = courses;
}

}

import {Component} from 'angular2/core';
import {CourseComponent} from './course.component'

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1><course></course>',
    directives:[CourseComponent],
    providers:[CourseComponent]
})
export class AppComponent {
private newCourses:string[];

public constructor(courseComponent: CourseComponent){
    courseComponent.setCourse(['java'])
}
 }

Its because you're trying to change variable of different instances. 这是因为您要更改不同实例的变量。

You could leverage ViewChild to get the instance CourseComponent which is defined within your template and only after ngAfterViewInit hook you can fire changes: 您可以利用ViewChild来获取实例模板中定义的CourseComponent实例,只有在ngAfterViewInit钩子之后,您才能触发更改:

@Component({
  selector: 'my-app',
  template: '<h1>My First Angular 2 App</h1><course></course>'
})
export class AppComponent {
  @ViewChild(CourseComponent) courseComponent;
  ngAfterViewInit() {
    this.courseComponent.setCourse(['java'])
  }
}

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

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