hex
hex

Reputation: 515

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. So it's supposed to show "java" instead of "x,y,z" but it doesn't.

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'])
}
 }

Upvotes: 0

Views: 439

Answers (1)

yurzui
yurzui

Reputation: 214175

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:

@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'])
  }
}

Upvotes: 1

Related Questions