亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Angular 中為響應式表單構建可重用字段

如何在 Angular 中為響應式表單構建可重用字段

江戶川亂折騰 2022-12-29 15:49:34
我正在嘗試為反應形式構建一個可重用的字段組件,但我無法從custom-input組件中獲取值。<form [formGroup]="form" (ngSubmit)="submit()">  <custom-input id="name" name="name" formControlName="name"></custom-input>  <button type="submit" name="button">Submit</button></form>我的自定義輸入可重用組件import { Component, OnInit, Input } from '@angular/core';import { FormControl } from "@angular/forms";@Component({  selector: 'custom-input',  template: '<input type="text" [class]="class" [id]="id" [name]="name" [formControlName]="formControlName">',  styles: []})export class CustomInputComponent implements OnInit {  @Input() public id: string;  @Input() public class: string;  @Input() public name: string;  @Input() public formControlName: string;  constructor() { }  ngOnInit() {  }}
查看完整描述

1 回答

?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

您可以實現ControlValueAccessor,但可能不想重新實現本機輸入的方法。為此,您可以使用FormControlDirective來訪問 valueAccessor。


formControl并formControlName作為輸入屬性添加,因此它在這兩種情況下都適用。如果formControlName提供,FormControl將從中檢索的實例ControlContainer。


@Component({

      selector: 'app-custom-input',

      template: `<input type="text" [formControl]="control">`,

      styleUrls: ['./custom-input.component.scss'],

      providers: [

        {

          provide: NG_VALUE_ACCESSOR,

          useExisting: CustomInputComponent,

          multi: true

        }

      ]

    })

    export class CustomInputComponent implements ControlValueAccessor {

      @Input() formControl: FormControl;

      @Input() formControlName: string;

    

      @ViewChild(FormControlDirective, {static: true})

      formControlDirective: FormControlDirective;

      private value: string;

      private disabled: boolean;

    

      constructor(private controlContainer: ControlContainer) {

      }

    

      get control() {

        return this.formControl || this.controlContainer.control.get(this.formControlName);

      }

    

    

      registerOnTouched(fn: any): void {

        this.formControlDirective.valueAccessor.registerOnTouched(fn);

      }

    

      registerOnChange(fn: any): void {

        this.formControlDirective.valueAccessor.registerOnChange(fn);

      }

    

      writeValue(obj: any): void {

        this.formControlDirective.valueAccessor.writeValue(obj);

      }

    }

來源:https ://medium.com/angular-in-depth/dont-reinvent-the-wheel-when-implementing-controlvalueaccessor-a0ed4ad0fafd


查看完整回答
反對 回復 2022-12-29
  • 1 回答
  • 0 關注
  • 82 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號