Angular 4 Notes (Part 3) - Directives, Events and Forms

Directives

There are 2 types of directive in Angular 4:
1. Attribute Directives (https://angular.io/guide/attribute-directives)
2. Structural Directives (https://angular.io/guide/structural-directives)

For now lets learn about Structural Directives.
Lets create an array called hobbies.

  hobbies: string[];

this.hobbies = ['gamming', 'travelling', 'coding'];


Lets use Angular's predefined directives for this example.
We are going to use ngFor (https://angular.io/api/common/NgForOf)

Go to your component template (user.component.html) and use this directive to populate the data in the array.

<h3>Hobbies</h3>
<ul>
  <li *ngFor = "let hobby of hobbies">{{hobby}}</li>
</ul>

You can use the Index if you want.

<ul>
  <li *ngFor = "let hobby of hobbies; let i = index">{{i + 1}} - {{hobby}}</li>
</ul>

This will list your hobbies in the array as bellow.


Events

This define as:
(event type) = function name

1. Defined a click event in user.component.html
<button (click) = "clickMe()">Click Me</button>

2. Define clickMe method in user.component.ts
clickMe(){
    this.data = 'I have been clicked.';
}

This will change the value of the label when the button get clicked.



Forms

Lets add a form to add new hobbies.

1. Add following code to the user.component.html

<h3>Hobbies</h3>
<form (submit)="addHobby(hobby.value)">
  <div>
    <label>Hobby: </label>
    <input type="text" #hobby/>
  </div>
</form>

# - used to define id (Ex: #hobby)

2. Add addHobby() method to user.component.ts

  addHobby(hobby:string){
    this.hobbies.push(hobby);
    return false;   
  }



Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#