Search code examples
angulartemplatesinputpropertiesangular2-changedetection

Angular change detection on input decorated property


If I decorate my property with @Input decorator and update it via some rest service, will a string interpolated property in a template be updated every time it changes?

In a component:

@Input()
myProperty: string;

In a template:

{{myProperty}}

Solution

  • You cannot use @Input to bind a value from a service (@Injectable), as @Input is specifically for passing values from a parent component to a child component via the parent's template:

    @Component({
        selector: 'app-parent',
        template: `<app-child [name]='name'></app-child>`
    })
    export class ParentComponent {
        name: string = "World";
    }
    
    @Component({
        selector: 'app-child',
        template: `<p>Hello, {{name}}!</p>`
    })
    export class ChildComponent {
        @Input() name: string;
    }
    

    You could bind to an Observable using the AsyncPipe (here I've created an Observable from a BehaviorSubject, but it could just as easily be returned from a method that makes an HTTP request via HttpClient):

    @Injectable({
        providedIn: 'root'
    })
    export class NameService implements OnInit {
        private name = new BehaviorSubject('');
        public name$ = this.name.asObservable();
    
        ngOnInit(): void {
            this.name.next('World');
        }
    }
    
    @Component({
        selector: 'app-child',
        template: `<p>Hello, {{nameService.name$ | async}}!</p>`
    })
    export class ChildComponent {    
        constructor(public nameService: NameService) { }
    }