在Stackblitz新版独立Angular启动模板中导入组件遇问题
问题:Angular独立组件导入报错
Stackblitz的Angular启动模板默认启用了新版独立组件,我尝试将自定义组件FirstComponent导入main.ts中声明的主组件时遇到问题。虽然已经给自定义组件添加了standalone: true和imports属性,但报错依旧。
自定义组件代码
import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-first', standalone: true, imports: [CommonModule], templateUrl: './first.component.html', styleUrls: ['./first.component.css'], }) export class FirstComponent implements OnInit { constructor() {} ngOnInit() {} }
Stackblitz默认main.ts代码
import 'zone.js/dist/zone'; import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; import { bootstrapApplication } from '@angular/platform-browser'; @Component({ selector: 'my-app', standalone: true, imports: [CommonModule], template: ` <h1>Hello from {{name}}!</h1> <a target="_blank" href="https://angular.io/start"> Learn more about Angular </a> <app-first></app-first> `, }) export class App { name = 'Angular'; } bootstrapApplication(App);
错误信息
Error in src/main.ts (15:5) 'app-first' is not a known element: 1. If 'app-first' is an Angular component, then verify that it is included in the '@Component.imports' of this component. 2. If 'app-first' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@Component.schemas' of this component to suppress this message.
解决方案
问题出在主组件App没有显式导入FirstComponent。在Angular独立组件体系中,要使用另一个独立组件,必须在当前组件的imports数组中添加该组件。
修改后的main.ts代码如下:
import 'zone.js/dist/zone'; import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; import { bootstrapApplication } from '@angular/platform-browser'; // 导入自定义组件(路径需匹配你的文件结构) import { FirstComponent } from './first/first.component'; @Component({ selector: 'my-app', standalone: true, imports: [CommonModule, FirstComponent], // 将FirstComponent加入imports数组 template: ` <h1>Hello from {{name}}!</h1> <a target="_blank" href="https://angular.io/start"> Learn more about Angular </a> <app-first></app-first> `, }) export class App { name = 'Angular'; } bootstrapApplication(App);
内容的提问来源于stack exchange,提问作者Dust_In_The_Wind
相关产品推荐
相关产品推荐

