1.13.1. fejezet, Interpoláció és kötések

Home.component.html

<p>Enter key event filter: <input (keyup.enter)="enterKeyPressed(enterevent,focusOnEnter)" #enterevent/></p>
 
<p>KeyUp event handler: <input (keyup)="keyPressed($event)" #focusOnEnter/></p>
 
<p>User name: <input [value]="userName" #username (keyup.enter)="updateUserName(username)"/></p>
 
<p>Two way data binding: <input [(ngModel)]="email" (keyup.enter)="saveEmail()"/></p>
 
<button [style.background]="isActive?'lime':'red'" (click)="buttonClick()">Click me</button>
 
<p>Entered e-mail: {{email}}</p>
 
<p>Profile e-mail: {{userProfile?.email}}</p>
 
<button (click)="logout()">LogOut</button>

Home.component.ts

import { Component, OnInit } from '@angular/core';
import { KeycloakAngularModule, KeycloakService } from 'keycloak-angular';
import { KeycloakProfile } from 'keycloak-js';
 
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrl: './home.component.css'
})
export class HomeComponent implements OnInit {
  isActive = true
  userName:string|undefined = "Papp Zoltán"
  email:string|undefined = "a@b.hu"
  public isLoggedIn = false;
  public userProfile: KeycloakProfile | null = null;
 
  constructor(private readonly keycloak: KeycloakService) {}
 
  public async ngOnInit() {
    this.isLoggedIn = this.keycloak.isLoggedIn();
 
    if (this.isLoggedIn) {
      this.userProfile = await this.keycloak.loadUserProfile();
      this.email = this.userProfile.email
      this.userName = `${this.userProfile.firstName} ${this.userProfile.lastName}`
    }
  }
 
  keyPressed(event: KeyboardEvent) {
    console.log(`Key pressed: ${event.key}`)
  }
 
  buttonClick() {
    this.isActive = !this.isActive
  }
 
  enterKeyPressed(enterEventElement: HTMLInputElement, focusOnEnter: HTMLInputElement) {
    console.log(`Entered value: ${enterEventElement.value}`)
    focusOnEnter.focus({ preventScroll: true })
  }
 
  updateUserName(userNameElement: HTMLInputElement) {
    this.userName = userNameElement.value
  }
 
  saveEmail() {
    console.log(`Email is ${this.email}`)
  }
 
  public logout() {
    this.keycloak.logout();
  }
}