要给出“Angular 7 组件”的代码示例,需要先创建一个新的 Angular 7 项目。下面是一个简单的步骤:
npm install -g @angular/cli
。这将全局安装 Angular CLI。ng new my-app
。将 my-app
替换为你想要的项目名称。cd my-app
。ng serve
。http://localhost:4200/
,你将看到一个包含“app works!”的页面。这表明你的 Angular 7 项目已成功运行。接下来,我们将创建一个简单的组件并添加一些代码示例。假设我们要创建一个名为 hello-world
的组件,用于显示“Hello, World!”。
ng generate component hello-world
。hello-world
目录:cd hello-world
。hello-world.component.ts
文件,并替换其内容为以下代码:import { Component } from '@angular/core';
@Component({
selector: 'app-hello-world',
template: 'Hello, World!
',
})
export class HelloWorldComponent {}
hello-world.component.html
文件,并删除其内容。cd ..
。app.component.html
文件,并将以下代码添加到文件的任意位置以引入 hello-world
组件:
http://localhost:4200/
上你将看到一个包含“Hello, World!”的页面。以上就是创建和使用一个简单的 Angular 7 组件的步骤和代码示例。你可以根据需要扩展和修改组件的代码。