第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何在 Angular 中為響應(yīng)式表單構(gòu)建可重用字段

如何在 Angular 中為響應(yīng)式表單構(gòu)建可重用字段

江戶川亂折騰 2022-12-29 15:49:34
我正在嘗試為反應(yīng)形式構(gòu)建一個(gè)可重用的字段組件,但我無法從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貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊

您可以實(shí)現(xiàn)ControlValueAccessor,但可能不想重新實(shí)現(xiàn)本機(jī)輸入的方法。為此,您可以使用FormControlDirective來訪問 valueAccessor。


formControl并formControlName作為輸入屬性添加,因此它在這兩種情況下都適用。如果formControlName提供,F(xiàn)ormControl將從中檢索的實(shí)例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


查看完整回答
反對 回復(fù) 2022-12-29
  • 1 回答
  • 0 關(guān)注
  • 81 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)