首页 > 解决方案 > Angular bind formcontrolname in sub component

问题描述

ok: I don't know if the caffeine isn't working, or what im overlooking, but i need the for-dummies on this one. I have a form, and a component within the form containing an input.

Here is the form template:

<div [formGroup]="parent">
  <h5 class="card-title">{{fieldLabel}}<audit-tooltip fieldName="fieldName" [plan]="plan"></audit-tooltip> </h5>
  <input [formControlName]="fieldName" class="form-control mx-sm-3 col-10" />
</div>

And here is the underlying typescript.

@Component({
  selector: 'info-control',
  templateUrl: './info-control.component.html',
  styleUrls: ['./info-control.component.css']
})
export class InfoControlComponent {
  @Input() fieldLabel: string;
  @Input() parent: FormGroup;
  @Input() plan: Plan;


  private _fieldName: string;
  @Input() public set fieldName(name: string) {
    this._fieldName = name;
  }
  public get fieldName(): string {
    return this._fieldName;
  }
}

And here is the implementation:

<form [formGroup]="disciplineForm" novalidate>
  <div class="card-body">
    <div class="row">
        <div class="col">
            <info-control [fieldLabel]="'Label Sample'" [parent]="disciplineForm" [fieldName]="'nameSample'" [plan]="plan"></info-control>
            <div class="invalid-tooltip">
              Length cannot exceed 50 characters.
            </div>
      </div>
      </div>
    </div>
</form>

I cannot seem to get [formControlName] or fieldName to show as "nameSample". If i include brackets I get nothing in the DOM -that attribute simply is ignored. If I remove them, then i get the literal string 'fieldName'.

What am I not understanding? This is my first angular 2+ app.

标签: angulardata-bindingcomponents

解决方案


fieldName您作为@Input属性传递给 的应该audit-tooltip与属性绑定语法一起使用。使用它,我能够通过fieldName并且它正在以nameSample.

就是这样:

<div [formGroup]="parent">
  <h5 class="card-title">
    {{fieldLabel}}<audit-tooltip [fieldName]="fieldName" [plan]="plan"></audit-tooltip>
  </h5>
  <input 
    [formControlName]="fieldName" 
    class="form-control mx-sm-3 col-10" />
</div>

如果你愿意,这里是StackBlitz 。


推荐阅读