Skip to content

User Input

Aakash Goplani edited this page Jul 28, 2019 · 12 revisions

Topics Covered

Taking input from user
Shadow DOM
View Encapsulation
ng-content

Taking input from user

  1. Template Reference Variable

    • A template reference variable is often a reference to a DOM element within a template. It can also refer to a directive (which contains a component), an element, TemplateRef, or a web component.
    • Use the hash symbol # to declare a reference variable. The following reference variable, #player, declares a player variable on an <input> element.
    • You can refer to a template reference variable anywhere within the component's template and NOT inside component. To access inside component, use ViewChild Here, a <button> further down the template refers to the player variable.
    <input #player placeholder="player name">
    <button (click)="playerDetails(player)">Call</button>
    OR
    <input #player placeholder="player name"> => {{player.value}} <!--refere directly-->
    playerDetails(playerName: HTMLInputElement) {
       this.playerName = playerName.value;
    }

    More on template Reference

  2. ViewChild() decorator

    • With ViewChild() decorator, we can reference template reference variable variable inside your component without passing it via method as a parameter.
    import {ViewChild, ElementRef} from '@angular/core';
    @ViewChild('viewChild', {static: false}) viewChildReferenceValue: ElementRef; 
    /* here viewChild is template reference variable */
    viewChildReference() {
     console.log(this.viewChildReferenceValue.nativeElement.value);
    }
    <input type="text" class="form-control" #viewChild/><br>
    <button class="btn btn-primary" (click)="viewChildReference()">View Child Reference</button>
    • In Angular 8, the @ViewChild() syntax add { static: true } as a second argument. It needs to be applied to ALL usages of @ViewChild() (and also @ContentChild()) If you plan on accessing the selected element inside of ngOnInit(). If you DON'T access the selected element in ngOnInit() (but anywhere else in your component), set static: false instead! This is a temporary adjustment which will NOT be required anymore once Angular 9 is released!
  3. Event Binding

    • With Form
    <form (ngSubmit)="onSubmit($event)">
     <input name="player" value="Name">
    </form>
    onSubmit(event: any) {
     return event.target.player.value;
    }
    • Without Form
    <input (keyup)="onKey($event)">
    onKey(event) {const inputValue = event.target.value;}
  4. Use ngModel i.e 2-way data binding

    <input type="text" [(ngModel)]="someString">
    someString: string = '';
  5. Must read article


Shadow DOM

View Encapsulation

ng-content

Clone this wiki locally