【问题标题】:Get parent's property from child component in angular form以角度形式从子组件中获取父级的属性
【发布时间】:2018-05-18 11:35:58
【问题描述】:

我正在使用带有反应表单的 Angular 6,我需要在可编辑视图和自定义“只读”视图之间切换表单。项目中有多个自定义输入组件,因此似乎最简单的方法是在 custom-form 元素上使用 [readOnly] 绑定。问题是:

如何在 custom-input 组件中获取父级的 readOnly 值而不直接绑定到每个组件?

例如:

带表格的模板

<custom-form formGroup="formGroup" [readOnly]="!(canEdit$ | async)">
  <custom-input formControlName="field1"></custom-input>
  <custom-input formControlName="field2"></custom-input>
  <custom-select formControlName="field3"></custom-select>
  ...
</custom-form>

自定义输入模板

// Show input if form readOnly is false
<input *ngIf="!formIsReadOnly"...>

// Show some other representation if not
<span *ngIf="formIsReadOnly">...</span>

【问题讨论】:

    标签: angular angular-forms angular-template


    【解决方案1】:

    如果您不想向自定义控件添加readonly 输入参数,那么您将需要每个控件从其构造函数中获取的服务或不透明令牌,以确定控件是否为只读.

    对于不透明的令牌,您需要在应用的根目录处提供一个布尔值,然后在任何时候想要更改它时都必须重新提供。

    服务 (Demo)

    如果您希望能够将只读值切换为关闭,则需要使用服务。

    只读.service.ts
    @Injectable()
    export class ReadonlyService {
      public readonly = false;
    }
    
    readonly.component.ts
    @Component({
      selector: 'app-readonly',
      templateUrl: './readonly.component.html',
      providers: [ReadonlyService],
    })
    export class ReadonlyComponent implements OnInit {
    
      constructor(public readonlyService: ReadonlyService) { }
    
      ngOnInit() {
        this.readonlyService.readonly = true;
      }
    }
    
    customInput.component.ts
    @Input() public value: any;
    constructor(public readonlyService: ReadonlyService) { }
    
    customInput.component.html
    <ng-container *ngIf="!readonlyService.readonly; else readonlyView">
      <input placeholder="Enter a value" [(ngModel)]="value">
    </ng-container>
    
    <ng-template #readonlyView>
      Your readonly value is: {{value}}
    </ng-template>
    

    【讨论】:

    • 谢谢!我从来没有想过以这种方式使用服务,太棒了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 2021-03-25
    • 2021-05-12
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    相关资源
    最近更新 更多