Component Inside Angular 2 Form

So here is my parent form:

<form [ngFormModel]="formModel">
    <ui-form-control *ngFor="#key of controlsKeys"
                     [control]="formModel.controls[key]"
                     [name]="key">
    </ui-form-control>
</form>

here is my component:

@Component({
    selector: 'ui-form-control'
})
@View({
    template: `
    <label>{{name}}: </label>
    <input [ngFormControl]="control" [placeholder]="name">
    `,
    directives: [FORM_DIRECTIVES]
})
export class UiFormControl{
    @Input() control: UiControl;
    @Input() name: string;

    constructor(){
    }
}

I can see the Control value inside my ui-form component, but when I change its formModel-ComponentGroup, it does not update. So it seems that two-way binding does not work here.

In fact, if I delete my own <ui-form-control>and place a simple tag <input>, it will work instead, and the formModel will be updated as expected.

+4
source share
2 answers

, @Input @Output. , . - :

@Component({
  selector: 'ui-form-control'
  template: `
    <label>{{name}}: </label>
    <input [ngFormControl]="control" (change)="inputChanged()" [placeholder]="name">
  `,
  directives: [FORM_DIRECTIVES]
})
export class UiFormControl{
  @Input() control: UiControl;
  @Output() controlChange: EventEmitter;
  @Input() name: string;

  constructor(){
    this.controlChange = new EventEmitter();
  }

  inputChanged() {
    this.controlChange.emit(this.control);
  }
}

, ng-content.

@Component({
  selector: 'field',
  template: `
    <div class="form-group form-group-sm" [ngClass]="{'has-error':control && !control.valid}">
      <label for="for"
         class="col-sm-3 control-label">{{label}}</label>

      <div #content class="col-sm-8">
        <ng-content ></ng-content>
        <span *ngIf="control && !control.valid" class="help-block text-danger">
          <span *ngIf="control?.errors?.required">The field is required</span>
        </span>
      </div>
    </div>
  `
})
export class FormFieldComponent {
  @Input()
  label: string;

  @Input()
  state: Control;
}

:

<form [ngFormModel]="companyForm">
  <field label="Name" [state]="companyForm.controls.name">
    <input [ngFormControl]="companyForm.controls.name" 
           [(ngModel)]="company.name"/> {{name.valid}}
  </field>
</form>

, , selects, textareas , (, Bootstrap3) , . , , ; -)

, , Thierry

+2

?

-, , . , :

<input [(ng-model)]="myField" >

.

-1

Source: https://habr.com/ru/post/1624081/


All Articles