Angular - 巢狀元件



在 Angular JS 中,可以在彼此內部巢狀元件。外部容器稱為父容器,內部容器稱為子容器。讓我們看一個如何實現此目的的示例。以下是步驟。

步驟 1 - 為名為 child.component.ts 的子容器建立一個 ts 檔案。

Child.components

步驟 2 - 在上述步驟中建立的檔案中,放置以下程式碼。

import { 
   Component 
} from '@angular/core';  

@Component ({ 
   selector: 'child-app', 
   template: '<div> {{values}} </div> ' 
}) 

export class ChildComponent { 
   values = ''; 
   ngOnInit() { 
      this.values = "Hello"; 
   } 
}

以上程式碼將引數 this.values 的值設定為“Hello”。

步驟 3 - 在 app.component.ts 檔案中,放置以下程式碼。

import { 
   Component 
} from '@angular/core'; 

import { 
   ChildComponent 
} from './child.component'; 

@Component ({ 
   selector: 'my-app', 
   template: '<child-app></child-app> ' 
}) 

export class AppComponent { }

在上面的程式碼中,請注意我們現在正在呼叫 import 語句來匯入 child.component 模組。我們還在從子元件呼叫 <child-app> 選擇器到我們的主元件。

步驟 4 - 接下來,我們需要確保子元件也包含在 app.module.ts 檔案中。

import { 
   NgModule 
} from '@angular/core'; 

import { 
   BrowserModule 
} from '@angular/platform-browser';  

import { 
   AppComponent 
} from './app.component';  

import { 
   MultiplierPipe 
} from './multiplier.pipe' 

import { 
   ChildComponent 
} from './child.component';  

@NgModule ({ 
   imports: [BrowserModule], 
   declarations: [AppComponent, MultiplierPipe, ChildComponent], 
   bootstrap: [AppComponent] 
}) 

export class AppModule {}

儲存所有程式碼更改並重新整理瀏覽器後,您將獲得以下輸出。

Nested Containers
廣告