【问题标题】:@Input() not working@Input() 不工作
【发布时间】:2018-04-04 09:50:10
【问题描述】:

我正在尝试使用 @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;
  }
}

【问题讨论】:

  • 您应该决定是使用服务还是使用输入来设置该属性。没有理由同时使用两者。
  • makeDisabled() 实际上应该设置this.isDisabled=true。你试过吗?
  • @bryan60 谢谢。我想我们不能同时使用 service 和 Input() 。如果我删除订阅然后输入工作正常!
  • 你是对的。如果您尝试在绑定之外更改输入绑定,则其中一种方式会中断。您也可以将其设置为 2 路绑定,这样就可以了,但是没有很好的论据来解释为什么要通过服务和输入来设置它。

标签: angular angular-components


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多