Angular - Forward component classes to child

Viewed 288

I have a custom input I use in a form

<form>
   <custom-input #refModel="ngModel" 
                 class="form-control" 
                 [class.errors]="refModel.errors" 
                 [(ngModel)]="myModel">
   </custom-input>
</form>

custom-input.component.html

<input type="text" [ngModel]="value" (ngModelChange)="onChange($event)" id="inner-input" />

I'd like the classes applied to custom-input to be applied to my inner-input instead (custom-input must not have any classes at the end).

Is it a good pattern? If so, how can I achieve it?

1 Answers

This can be achieved by using an @Input property to receive the class, [ngClass] to apply it, and ElementRef to clear it from the parent.

@Component({
  selector: 'custom-input',
  templateUrl: './custom-input.component.html'
})
export class CustomInputComponent implements OnInit {
  @Input('class') inputClass: string;

  constructor(private element: ElementRef<HTMLElement>) { }

  ngOnInit() {
    this.element.nativeElement.className = '';
  }
}
<input type="text" [ngClass]="inputClass">

<custom-input class="a-class b-class"></custom-input>

https://stackblitz.com/edit/angular-vqsvop

Related