Update parent component property from child component in Angular 2

前端 未结 4 575
北海茫月
北海茫月 2020-11-30 23:44

I\'m using @input to receive a property from parent component in order to activate a CSS class in one of child component\'s element.

I\'m able to receiv

相关标签:
4条回答
  • 2020-11-30 23:51

    Edited your code a little bit, it works and looks simplier imo. Tell me if you like it.

    https://plnkr.co/edit/oJOjEZfAfx8iKZmzB3NY?p=preview

    0 讨论(0)
  • 2020-11-30 23:56

    Another approach: use rxjs/BehaviorSubject to pass status between different components.
    Here's the plunkr.
    I name subject with a suffix 'Rxx', so the BehaviorSubject for searchStatus will be searchStatusRxx.

    1. initialize it in parent component like searchStatusRxx = new BehaviorSubject(false);,
    2. pass it to child component using @Input
    3. in child template, you do async pipe.
    4. in both parent and child, you do searchStatusRxx.next(value) to change the latest value.
    0 讨论(0)
  • 2020-12-01 00:01

    You need to use 2 way data-binding.

    @Input() is one way data-binding. to enable 2 way data-binding you need to add an @Output() corresponding to the property, with a "Change" suffix

    @Input() getSearchStatus: boolean;
    @Output() getSearchStatusChange = new EventEmitter<boolean>();
    

    when you want to publish the change made to your property to the parent, you need to notify the parent with:

    this.getSearchStatusChange.emit(newValue)
    

    and in the parent you need to use the banana-in-a-box notation for that property:

    [(getSearchStatus)]="myBoundProperty"
    

    you can also bind to the property and trigger a callback when it changes in child:

    [getSearchStatus]="myBoundProperty" (getSearchStatusChange)="myCrazyCallback($event)"
    

    see the plnkr

    0 讨论(0)
  • 2020-12-01 00:14

    Yet another way. Plunkr. What we want is a single source of truth. We can put that in child this time.

    • Init in child: searchStatus = false
    • In parent template, get the instance of child as #as or whatever name.
    • Change searchStatus in parent using #as.searchStatus and in child this.searchStatus.
    0 讨论(0)
提交回复
热议问题