Angular 2 ContentChild Apply Html Attributes

2019-07-29 18:18发布

问题:

I have a custom component that applies bootstrap form group to my form fields. In my component I have below properties:

import { Component, Input, ContentChild } from '@angular/core';
import { NgControl } from '@angular/common';

@Component({
    selector: 'form-field',
    template: `
            <div class="form-group" [ngClass]="{'has-error':(state && !state.valid && state.touched)}">
                <label *ngIf="label" [attr.for]="state.name" class="col-sm-3 control-label">{{label}}</label>
                <div class="col-sm-9">
                    <ng-content></ng-content>
                    <div *ngIf="state && !state.valid && state.errors && state.touched" class="help-block text-danger">
                        <span *ngIf="state.errors.required">{{label? label:'This field'}} is required</span>
                        <span *ngIf="state.errors.min">{{label? label:'Value'}} too small</span>
                    </div>
                </div>
            </div>
            `
})
export class FormFieldComponent{
    @Input()
    label: string;

    @ContentChild(NgControl) state;
}

And in my template I use my component like this:

<form [ngFormModel]="form" (ngSubmit)="onSubmit()" novalidate>
    <form-field label="First Name">
     <input ngControl="firstName" type="text">
    </form-field>
</form>

I was wondering is there any way to dynamically set the placeholder text for the control through my component?

I want the label to be set as placeholder of the input field i.e.

回答1:

This directive is applied to all input elements that have a ngControl or [ngControl]="..." attribute. It sets the placeholder attribute on the element where it is applied.

It is made globally available using

bootstrap(App, [
  provide(PLATFORM_DIRECTIVES, {useValue: [InputLabel], multi: true})
])
@Directive({
  selector: ['[ngControl]']
})
export class InputLabel {
  @Input()
  @HostBinding('attr.placeholder') 
  label;

  constructor() {
    console.log('InputLabel');
  }
}

In the FormField component this directive is queried for and the label from the input is passed to the directive (in ngOnChanges or ngAfterContentChecked - basically the first occurence where label and state are available.

@Component({
  selector: 'form-field',
  providers: [],
  template: `
    <div>
      <ng-content></ng-content>
    </div>
  `,
  directives: []
})
export class FormField {
  @Input() label: string;
  @ContentChild(InputLabel) state;

  ngOnChanges() {
    if(this.label && this.state) {
      this.state.label = this.label;
    }
  }

  ngAfterContentInit() {
    if(this.label && this.state) {
      this.state.label = this.label;
    }
  }
}

This is just to demonstrate how its used:

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
<form>      
  <form-field label="First Name">
    <input ngControl="firstName" type="text">
  </form-field>      
</form>
    </div>
  `,
  directives: [FormField, FORM_DIRECTIVES]
})
export class App {

  constructor(fb:FormBuilder) {
    this.name = 'Angular2 (Release Candidate!)'
    this.form = fb.group({firstName: [""]});
  }
}

Plunker example

I choose this approach because I wasn't able to query by something else (NgControl, ...) and get a reference to the input element.

It's not necessary to provide the directive this way. It can also be provided like any other custom directive by adding it to directives: [InputLabel] on the @Component() decorator where it is used.



回答2:

You could bind your label to "placeholder"

form-field label="First Name">
 <input ngControl="firstName" type="text" [attr.placeholder]="label">
</form-field>