@Input()不起作用

时间:2017-10-23 18:37:41

标签: angular angular-components

我正在尝试使用@Input()从父组件更改子组件属性,但它不起作用。我使用共享服务工作但我确实理解我做错了什么以及为什么它不使用@Input()

我在子组件中创建了2个按钮,其中的文本来自父组件的@Input()数据对象。当我双击表行时,其中有两个按钮,使用@Input()isDisabled属性使用共享服务禁用按钮。当我单击父组件中的 get 按钮时,数据更改和更改会得到反映。但是当我尝试使用父组件中的isDisabled = false启用按钮时,更改不会反映出来。

以下是codepen示例的链接:angular 4 codepen example

子组件

import { Component, Input, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { DataService } from './data.service'

@Component({
    selector: 'tr[app-myComp]',
    template: `
                    <td><button [disabled]="isDisabled">{{data.prop1}}</button></td>    
                    <td><button [disabled]="isDisabled">{{data.prop2}}</button></td>    
                `
})

export class MyComponent implements OnInit {
  subscription: Subscription;

  @Input()
  isDisabled: boolean;

  @Input()
  data: {prop1: number, prop2: number};

    constructor(public service: DataService) {
this.subscription = service.disabled$.subscribe(
            () => {
                    this.isDisabled = true;
            }
        );
    }

  ngOnInit() {}

  ngOnDestroy(){
    this.subscription.unsubscribe();
  }

}

父组件

import { AfterViewInit, Component, QueryList, ViewChildren } from '@angular/core';

import { MyComponent } from './myComponent'
import { DataService } from './data.service'

@Component({
  selector: 'app-body',
  template: `<table>
                <tr class="">
                  <td>buttons</td>
                </tr>
                <tr app-myComp [isDisabled]="isDisabled" [data]="data" [isDisabled]="isDisabled" (dblclick)="makeDisabled()"></tr>
             </table>

<button (click)="getNewData()">Get</button>
            `,
})
export class AppComponent implements AfterViewInit  {

  constructor(
    public service: DataService
  ){}

  isDisabled: boolean = false;
  data: {prop1: number, prop2: number} = {prop1: 13, prop2: 16};

  makeDisabled(): void {
    this.service.makeDisabled()
  }

  getNewData(): void {
    //service call
    this.data = {prop1: 45, prop2: 56};
    this.isDisabled = !this.isDisabled;
    this.isDisabled = false;
  }
}

1 个答案:

答案 0 :(得分:0)

在您的构造函数中,您订阅了disabled$,但在订阅中,您将this.isDisabled设置为false而不是订阅中的值。尝试将其更改为:

&#13;
&#13;
constructor(public service: DataService) {
  this.subscription = service.disabled$.subscribe(
    (isDisabled: boolean) => {
      this.isDisabled = isDisabled;
    }
  );
}
&#13;
&#13;
&#13;