1/10/2019

ngIf

There are times where you may need to hide or show content based off a condition in JavaScript. In the past, we've use CSS and classes to hide elements. We can use ngIf to show or hide content.

NgIf actually adds and removes content from the DOM when its condition is triggered.

Syntax


@Component({
  selector: 'my-app',
  template: `
       <input id="textField" value="" />
       <span *ngIf="isInvalid">First name is Invalid</span>
    `
})
export class AppComponent {
    if (txtField == ''){
        isInvalid = true
    }
}
        

Else


Visible shown content

Hidden else content

ngFor

ngFor allows you to loop through and display an array of objects in the view.

Syntax


export class AppComponent {
  names = ['Ted', 
    'Fred', 
    'Marco', 
    'Polo'];
}

  • {{name}}

Output


  • Ted
  • Fred
  • Marco
  • Polo

Component Styles

Styling components in Angular is different than traditional styling.

Inline Syntax


@Component({
  selector: 'app-comp',
  template: `
    

Hello Angular

`, styles: [` h1 { font-weight: normal; } h2 { font-weight: bold; } `] }) export class HeroAppComponent { /* . . . */ }

External Syntax


@Component({
  selector: 'app-comp',
  template: `
    

Hello Angular

`, styleUrls: ['app.component.css'] }) export class HeroAppComponent { /* . . . */ }

CSS Encapsulation


@Component({
  selector: 'app-comp',
  template: `
    

Hello Angular

`, styles: [` h1 { font-weight: normal; } h2 { font-weight: bold; } `] }) export class HeroAppComponent { /* . . . */ }

<h1 _ngcontent-pmm-1>Hello Angular</h1>

h1[_ngcontent-pmm-1] { font-weight: normal; }

Encapsulation Continued

  • The styles specified in @Component metadata apply only within the template of that component.
  • They are not inherited by any components nested within the template nor by any content projected into the component.
  • Angular generates custom attributes to help scope our CSS class names to our given component.

Docs

PrimeNG

For "common" components, don't build your own. Use a library like PrimeNG and override the styling for your project.

Docs

>