Tuesday, 29 May 2018

Angular - Intercept input property changes with a setter

Use an input property setter to intercept and act upon a value from the parent.
The setter of the name input property in the child NameChildComponent trims the whitespace from a name and replaces an empty value with default text.
component-interaction/src/app/name-child.component.ts
import { Component, Input } from '@angular/core';

  selector: 'app-name-child',
  template: '<h3>"{{name}}"</h3>'
})
export class NameChildComponent {
  private _name = '';

  @Input()
  set name(name: string) {
    this._name = (name && name.trim()) || '<no name set>';
  }

  get name(): string { return this._name; }
}
Here's the NameParentComponent demonstrating name variations including a name with all spaces:
component-interaction/src/app/name-parent.component.ts
import { Component } from '@angular/core';

  selector: 'app-name-parent',
  template: `
  <h2>Master controls {{names.length}} names</h2>
  <app-name-child *ngFor="let name of names" [name]="name"></app-name-child>
  `
})
export class NameParentComponent {
  // Displays 'Mr. IQ', '<no name set>', 'Bombasto'
  names = ['Mr. IQ', '   ', '  Bombasto  '];
}














No comments:

Post a Comment