简体   繁体   中英

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}}

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) { }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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