18
Tháng 11Cách thiết lập tiêu đề (title) tài liệu trong Angular
Trong hướng dẫn này, chúng ta sẽ tìm hiểu cách thiết lập tiêu đề tài liệu trong angular sử dụng TitleService.
Dịch vụ Title là gì?
Dịch vụ Title là một API đơn giản được sử dụng để thiết lập và lấy tiêu đề của tài liệu tới trang web hiện tại. Nó là một phần của angular Browser platform.
Phương thức getTitle()
: Được sử dụng để lấy tiêu đề.
Phương thức setTitle()
: Được sử dụng để thiết lập tiêu đề.
Thiết lập tiêu đề của tài liệu
Để sử dụng dịch vụ Title trong các component của chúng ta, đầu tiên chúng ta cần đăng ký một Title Service trong module ứng dụng gốc đó là tập tin app.module.ts
.
Mở tập tin app.module.ts
và import dịch vụ Title
từ gói @angular/platform-browser
sau đó thêm nó tới mảng providers
.
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule, Title } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent ],
providers: [Title], bootstrap: [ AppComponent ]
export class AppModule { }
Bây giờ, chúng ta có thể thiết lập một tiêu đề tài liệu mới bằng việc bổ sung dịch vụ Title
vào trong constructor của Component
.
app.component.ts
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
export class AppComponent {
Tương tự, bạn có thể sử dụng cùng thủ tục để thiết lập tiêu đề tài liệu tới các component điều hướng khác trong ứng dụng angular.
contact.component.ts
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: [ './contact.component.css' ]
export class ContactComponent {
Đánh giá