目录

Angular 2 - 嵌套容器( Nested Containers)

在Angular JS中,可以将容器嵌套在彼此内部。 外部容器称为父容器,内部容器称为子容器。 让我们看看如何实现这一目标的示例。 以下是步骤。

Step 1 - 为名为child.component.ts的子容器创建一个ts文件。

Child.components

Step 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”。

Step 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”选择器到我们的主要组件。

Step 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 {}

保存所有代码更改并刷新浏览器后,您将获得以下输出。

嵌套容器
↑回到顶部↑
WIKI教程 @2018