繁体   English   中英

在 Angular Reactive forms 中创建可重用的自定义 select 下拉组件

[英]Create a reusable custom select dropdown component in Angular Reactive forms

我正在尝试在Angular Reactive Forms中创建一个自定义的可重用选择输入组件。 该组件应以父组件形式使用(在我的情况下为注册表单)。 但我无法检测到子组件(选择输入组件)的更改将它们传递给父组件。 这是我尝试过的

选择输入.component.ts

@Component({
  selector: 'select-input',
  templateUrl: './select-input.component.html',
  styleUrls: ['./select-input.component.css']
})
export class SelectInputComponent implements ControlValueAccessor 
{
  @Input() label: string;
  @Input() name: string;
  @Input() options: {value: string}[];
  
  constructor() { }

  writeValue(obj: any): void
  {
    
  }
  registerOnChange(fn: any): void
  {
    
  }
  registerOnTouched(fn: any): void
  {
    
  }
}  

选择输入.component.html

<div>
    <label for={{name}} style="margin-right: 2px;">{{label}}:</label>
    <select name={{name}}>
        <option *ngFor="let option of options" [value]="option.value">
            {{option.value}}
        </option>
    </select>
</div>

注册组件.ts

export class RegisterComponent implements OnInit 
{
  countries: {name: string}[] = [
    {value: 'Canada'},
    {value: 'USA'},
    {value: 'UK'},
    {value: 'Japan'},
  ]
  registerForm: FormGroup;

  constructor (private fb: FormBuilder) {}

  ngOnInit(): void 
  {
    this.initializeForm();
  }
  
  initializeForm()
  {
    this.registerForm = this.fb.group({
      username: ['', Validators.required],
      country: [this.countries]
    })
    
  }
}

register.component.html

<select-input [formControl]='registerForm.controls["country"]' ngDefaultControl
        [label]='"Country"' [name]='"countries"' [options]="countries">
</select-input>

如何检测子组件(选择输入)的更改并将它们传播到父组件(注册表单)?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM