FresherKỹ thuậtAngular
Decorator @Component nhận những metadata nào?
Thử trả lời trước
Đáp án mẫu
Decorator @Component cho Angular biết cách tạo và render một class thành component. Các tùy chọn phổ biến nhất là:
selector: tên thẻ HTML dùng để đặt component, ví dụapp-user-card.templatehoặctemplateUrl: HTML viết trực tiếp hoặc đường dẫn tới file HTML.styles,styleUrlhoặcstyleUrls: CSS có phạm vi trong component.imports: các component, directive và pipe dùng trong template.changeDetection:DefaulthoặcOnPush.providers: service được tạo cho component này và các component con.
@Component({
selector: 'app-user-card',
imports: [DatePipe],
template: `<p>{{ joined | date }}</p>`,
styles: `p { color: gray; }`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UserCard {
joined = new Date()
}
Một số tùy chọn khác bạn có thể gặp là encapsulation, host và animations. Trong Angular hiện tại component mặc định là standalone. Cờ standalone: true trong code cũ giờ đã thừa.
Hãy nhớ các phần bắt buộc: selector và template.
Ý chính
- selector đặt tên thẻ HTML
- template hoặc templateUrl định nghĩa view
- imports liệt kê những gì template dùng
- changeDetection và providers tinh chỉnh hành vi
Câu hỏi nối tiếp thường gặp
- Tùy chọn encapsulation thay đổi điều gì?
Lỗi thường gặp
- Quên liệt kê component hoặc pipe đã dùng trong imports
- Vẫn viết standalone true như thể nó bắt buộc