用ng new my-ng-app --standalone=false
创建了一个angular应用,项目布局为:
自动生成的package.json文件为:
{
"name": "my-ng-app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^18.1.0",
"@angular/common": "^18.1.0",
"@angular/compiler": "^18.1.0",
"@angular/core": "^18.1.0",
"@angular/forms": "^18.1.0",
"@angular/platform-browser": "^18.1.0",
"@angular/platform-browser-dynamic": "^18.1.0",
"@angular/router": "^18.1.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^18.1.4",
"@angular/cli": "^18.1.4",
"@angular/compiler-cli": "^18.1.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.5.2"
}
}
制作组件方式一:手动方式
编写组件代码
在app目录下新建一个目录myc01,然后在该目录下新建三个文件:
为了写插件有提示,可以先在vscode中安装下面两款插件:
编写myc01.component.ts的代码:
输入ng-component,然后回车:
自动生成了模版式的代码:
修改以后:
编写myc01.component.html:
编写myc01.component.css:
注册组件
组件制作完毕,必须注册到全局中,才能使用。
在app.module.ts文件中注册。
使用组件
在根组件app.component.html中使用:
展示效果:
制作组件方式二:用命令快速生成组件
https://angular.cn/cli/generate/component
语法形式:
ng generate component 组件名 [选项]
简写形式:
ng g c 组件名 [选项]
例如,在vscode集成中终端中输入命令ng g c myc03
:
自动更新了app.module.ts文件:
自动生成的myc03.component.ts文件的内容:
自动生成的myc03.component.html文件的内容:
自动生成的myc03.component.css文件的内容:
到根组件app.component.html中使用,看看是否正常:
自动联想提示:
展示效果: