【问题标题】:How to pass formarray to other component如何将formarray传递给其他组件
【发布时间】:2019-03-22 03:42:37
【问题描述】:

我想将 formarray 传递给子组件以在那里显示 formarray 值。下面是代码,到目前为止我已经尝试过。我无法找到在子组件中显示 formarray 值的方法。

app.component.html

<div [formGroup]="userForm">
  <div formArrayName="users">
    <div *ngFor="let user of users.controls; let i = index">
      <input type="text" placeholder="Enter a Room Name" [formControlName]="i">
    </div>
  </div>
</div>
<button (click)="addUser()">Add Room</button>
<title [users]="users"></title>

app.component.ts

userForm: FormGroup;

constructor(private fb: FormBuilder) {}

public get users(): any {
  return this.userForm.get('users') as FormArray;
}

ngOnInit() {
  this.userForm = this.fb.group({
    users: this.fb.array([this.fb.control('')])
  });
}

addUser() {
  this.users.push(this.fb.control(''));
}

title.component.html

<div *ngFor="let user of users.controls">{{ user.value }}</div>

title.component.ts

@Input() users;

ngOnChanges(changes) {
  console.log(changes);
}

但是上面的代码没有在子组件中显示formarray的值。

stackblitz 示例为 here

【问题讨论】:

    标签: javascript angular typescript angular-reactive-forms formarray


    【解决方案1】:

    title 是一个关键字,它已经用 HTML 定义了标签。只需为组件使用一些不同的名称 selector

     selector: 'title1',
    

    STACKBLITZ DEMO

    【讨论】:

    • 是的,没错。现在工作正常。我可以在 10 分钟后接受你的回答 :-)
    猜你喜欢
    • 2019-04-03
    • 1970-01-01
    • 2021-08-15
    • 2020-12-30
    • 1970-01-01
    • 2019-04-07
    • 2017-08-23
    • 2017-07-29
    • 2021-11-15
    相关资源
    最近更新 更多