【问题标题】:Set value in child component that uses ControlValueAccessor from parent component在使用父组件的 ControlValueAccessor 的子组件中设置值
【发布时间】:2020-06-25 18:38:56
【问题描述】:

如果我在父组件中应用子组件(使用 ControlValueAccessor)并在子组件中写入内容,则所有内容都会相应地传递给父组件。

但是,如果我尝试在父组件中编写一些内容,然后将其传递给子组件,则输入中没有可用的内容。我该如何解决这个问题?

需要明确的是,这应该是首选行为:

child string value = written in child
parent string value = written in child

但每当我在父输入中输入文本时,我都会得到以下信息:

child string value = (empty)
parent string value = written in parent

[app.component.ts]

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  external = "";
}

[app.component.html]

<p>
  Start editing to see some magic happen :)
</p>
<app-custom-input [(ngModel)]="external" name="externalVal"></app-custom-input>
<input [(ngModel)]="external"/>
external: {{ external }}

[自定义输入.component.ts]

import { Component, forwardRef, HostBinding, Input, SimpleChanges } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";

@Component({
  selector: 'app-custom-input',
  template: '<input [(ngModel)]="value"/>local: {{val}}',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true
    }
  ]
})
export class CustomInputComponent implements ControlValueAccessor {
  onChange: any = () => {};
  onTouch: any = () => {};
  val = "";

  set value(val) {
    if (val !== undefined && this.val !== val) {
      this.val = val;
      this.onChange(val);
      this.onTouch(val);
    }
  }

  writeValue(value: any) {
    this.value = value;
  }

  registerOnChange(fn: any) {
    this.onChange = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouch = fn;
  }
}

也可在:https://stackblitz.com/edit/angular-ivy-ker4g5?file=src%2Fapp%2Fcustom-input%2Fcustom-input.component.ts

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    我认为问题在于您没有为 value 定义 getter。所以你必须修改你的代码如下:

    custom-input.component.ts

    set value (val) {
      /* ... */
    }
    
    get value () {
      return this.val
    }
    

    这是一个简化的例子:

    o = {
     _n: null,
     set name (v) {
       this._n = v;
     },
     get name () {
       return this._n;
     }
    }
    
    // Setter
    o.name = 'foo'
    
    // Getter
    // Without `get name()` -> `undefined`
    o.name
    

    【讨论】:

    • 我刚刚试了一下,你说的完全正确。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 2021-09-19
    • 2021-12-27
    • 1970-01-01
    • 2021-09-07
    • 2017-03-27
    • 1970-01-01
    相关资源
    最近更新 更多