Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design
Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Add custom class to body depending on a component - Angular

Sometimes the app that is being developed requires different classes on body of html document for styling each route or page. This can be achieved in Angular 2, Angular 4 and above using the following snippet.


Home Component
...//other code above
export class HomeComponent implements OnInit, OnDestroy {
 ngOnInit(){
    const body = document.getElementsByTagName('body')[0];
    body.classList.add('page-home');
  }

  ngOnDestroy(){
    const body = document.getElementsByTagName('body')[0];
    body.classList.remove('page-home');
  }
...//other code below

Dashboard Component
...//other code above
export class DashboardComponent implements OnInit, OnDestroy {
 ngOnInit(){
    const body = document.getElementsByTagName('body')[0];
    body.classList.add('page-dashboard');
  }

  ngOnDestroy(){
    const body = document.getElementsByTagName('body')[0];
    body.classList.remove('page-dashboard');
  }
...//other code below


AngularJS First Basic Demo For Beginners

In this demo we are going to use a simple text box, label and one button. This demo is for beginners.



I am going to do following things in this demo.

  • Add a Input field which updates a 'username'
  • Output the username property via String Interpolation
  • Add a button which may only be clicked if the username is NOT an empty string
  • Upon clicking the button, the username should be reset to an empty string

Here is the html code

<input 
  type="text" 
  class="form-control" 
  (input)="updateUserName($event)"
  [(ngModel)]="uName"
/>

<p>User Name is: {{ userName }}</p>

<button class="btn btn-primary"
[disabled]='!allowReset'
(click)="resetUserName()">Reset</button>

And here is the TypeScript file code

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-assignment',
  templateUrl: './assignment.component.html',
  styleUrls: ['./assignment.component.css']
})
export class AssignmentComponent implements OnInit {
  allowReset = false;
  userName = "";
  uName = "";

  constructor() { }

  ngOnInit() {
  }

  updateUserName(event: Event){
    this.userName = (<HTMLInputElement>event.target).value;
    this.allowReset = true;

    if(this.userName == ""){
      this.allowReset = false;
    }
  }

  resetUserName(){
    this.userName = "";
    this.uName = "";
    this.allowReset = false;
  }

}

 

Copyright @ 2017 HKBlog.