【问题标题】:Reusable input components using Angular 9 and Material design使用 Angular 9 和 Material 设计的可重用输入组件
【发布时间】:2020-07-31 04:44:21
【问题描述】:

我正在尝试使用 Angular 9 和材料设计创建一个可重用的输入组件。类似于下图。

TextboxComponent.html

<mat-form-field appearance="fill">
    <mat-label>Input</mat-label>
    <input matInput formControlName = {{imeta.formControlName}}>
</mat-form-field>

TextboxComponent.ts

@Component({
   selector: 'app-textbox',
   templateUrl: './textbox.component.html',
   styleUrls: ['./textbox.component.scss']
  })
export class TextboxComponent implements OnInit {
  @Input()imeta : IMeta
  constructor() { }
  ngOnInit(): void {}
}

export class IMeta {
    component: ComponentType;
    formControlName : string = null;
}

export enum ComponentType {
    TextBox = 0,
    TextArea = 1,
    RadioButton = 2,
    Checkbox = 3,
    Select = 4
}

这是一个可配置的组件,就像一座桥梁。

reactive-base-inputs.component.html

<ng-container [ngSwitch]="imeta.component">
    <ng-template [ngSwitchCase]="componentType.TextBox">
        <app-textbox [imeta]="imeta"></app-textbox>
    </ng-template>
</ng-container>

@Component({
  selector: 'reactive-inputs',
  templateUrl: './reactive-base-inputs.component.html',
  styleUrls: ['./reactive-base-inputs.component.scss']
})
export class ReactiveBaseInputsComponent implements OnInit {
  @Input() imeta : IMeta;
  componentType = ComponentType
  constructor() { }

  ngOnInit(): void {}
}

这是我使用输入组件的地方。

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <reactive-inputs [imeta]="configuration"></reactive-inputs>
</form>

我遇到了 formControlName 获取和设置的问题,我不知道如何设置 formControlName 并从父组件访问控件。

【问题讨论】:

    标签: angular typescript angular-material angular-forms angular9


    【解决方案1】:

    我有同样的问题,在搜索时我发现了 2 篇对我有很大帮助的文章。我设法创建了可重用的 Material 组件。

    https://inglkruiz.github.io/angular-material-reusable-autocomplete/

    https://ritchiejacobs.be/angular-custom-form-component

    创建可重用组件时的重点是从使用它的组件访问可重用组件的值。这可以通过 ControlValueAccessor 接口完成。

    希望对您有所帮助!

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    相关资源
    最近更新 更多