Truyền dữ liệu từ component con lên component cha trong Angular

Giới thiệu nội dung bài viết

Chào các bạn, hôm nay anh sẽ hướng dẫn mọi người cách component con lên component cha là như thế nào?

1.Truyền dữ liệu từ component con lên component cha

Chúng ta có 3 cách để truyền dữ liệu lên component cha từ component con. Chúng ta sẽ lần lượt đi qua các cách.

2.Ví dụ truyền dữ liệu từ con lên cha qua sự kiện

Trong ví dụ sau ta sẽ truyền giá trị từ component con qua component cha thông qua sự kiện. Trong component con ta sẽ sử dụng EventBinding để lắng nghe sự thay đổi data từ component con.

Ta có component con tên child.component.ts như sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Component, Input, Output, EventEmitter  } from '@angular/core';
 
@Component({
    selector: 'child-component',
    template: '<h2>Child Component</h2>
               <button (click)="increment()">Increment</button>
               <button (click)="decrement()">decrement</button>
               current count is 8'
})
export class ChildComponent {
    @Input() count: number;
 
    @Output() countChanged: EventEmitter<number> =   new EventEmitter();
 
    increment() {
        this.count++;
        this.countChanged.emit(this.count);
      }
    decrement() {
        this.count--;
        this.countChanged.emit(this.count);
    }
}

Đầu tiên chúng ta import thư viện output và EventEmitter từ angular core.

1
import { Component, Input, Output, EventEmitter } from '@angular/core';

Trong file template html ta có 2 nút buttons dùng để tăng và giảm biến count.

1
2
3
4
5
6
7
@Component({
    selector: 'child-component',
    template: '<h2>Child Component</h2>
               <button (click)="increment()">Increment</button>
               <button (click)="decrement()">decrement</button>
               current count is 8'
})

Trong component con chúng ta định nghĩa sự kiện countChange là loại EventEmitter và đặt cho nó annotation @Output để component cha có thể làm việc được với component con và để component cha thấy được sự kiện phát sinh từ component con.

1
@Output() countChanged: EventEmitter<number> = new EventEmitter();

Cuối cùng component con phát sinh sự kiện lên cho cha thông qua phương thức emit.

1
2
3
4
5
6
7
8
increment() {
        this.count++;
        this.countChanged.emit(this.count);
      }
    decrement() {
        this.count--;
        this.countChanged.emit(this.count);
    }

Trong Parent component chúng ta bắt lại sự kiện từ component con và xử lý như sau:

1
2
3
<child-component [count]=ClickCounter (countChanged)='countChangedHandler($event)'>
</child-component>
    

Trong component cha ta viết hàm countChangedHandler để xử lý sự kiện từ component con.

1
2
3
4
countChangedHandler(count: number) {
    this.ClickCounter = count;
    console.log(count);
  }

3.Ví dụ truyền dữ liệu từ con lên cha qua biến cục bộ

Chúng ta có lớp component con như sau. Chúng ta xoá đi input, output và event emitter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Component} from '@angular/core';
 
@Component({
    selector: 'child-component',
    template: '<h2>Child Component</h2>
               current count is 8'
})
export class ChildComponent {
    count = 0;
 
     increment() {
        this.count++;
      }
    decrement() {
        this.count--;
    }
}

Chúng ta có component cha như sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { Component} from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: '
        <h1>!</h1>
        <p> current count is  </p>
        <button (click)="child.increment()">Increment</button>
        <button (click)="child.decrement()">decrement</button>
        <child-component #child></child-component>' ,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Parent interacts with child via local variable';
}

Chúng ta tạo biến tên #child trong thẻ child-component. Biến này còn được gọi là biến template. Nó sẽ được hiển thị ở component con.

1
<child-component #child></child-component>

Bây giờ chúng ta sử dụng biến local template child để gọi các method và thuộc tính trong component con.

1
2
  <button (click)="child.increment()">Increment</button>
  <button (click)="child.decrement()">decrement</button>

4.Ví dụ truyền dữ liệu từ con lên cha qua ViewChild

Chúng ta có thể nhúng instance của component con vào cha thông qua annotation @ViewChild. Dựa vào ViewChild component cha có thể gọi được các phương thức và thuộc tính của component cha.

Ví dụ ta có component cha như sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
 
@Component({
  selector: 'app-root',
  template: '
        <h1></h1>
        <p> current count is  </p>
        <button (click)="increment()">Increment</button>
        <button (click)="decrement()">decrement</button>
        <child-component></child-component>' ,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Parent calls an @ViewChild()';
 
  @ViewChild(ChildComponent) child: ChildComponent;
 
  increment() {
    this.child.increment();
  }
 
  decrement() {
    this.child.decrement();
  }
}
 

Đầu tiên ta import ViewChild từ angular core.

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

Tiếp đến chúng ta tạo biến ViewChild và annotation là @ViewChild

1
@ViewChild(ChildComponent) child: ChildComponent;

Cuối cùng ta add thêm phương thức increment và decrement. Các phương thức này sẽ gọi hàm increase và decrement từ component con.

1
2
3
4
5
6
7
increment() {
    this.child.increment();
  }
 
  decrement() {
    this.child.decrement();
  }

5. Demo Video

6. Source code

Sourcecode


Mọi người hãy Subscribe kênh youtube dưới đây nhé để cập nhật các video mới nhất về kỹ thuật và kỹ năng mềm

Các khoá học lập trình MIỄN PHÍ tại đây


Comments