ser*_*kov 2 angular stackblitz
我在 StackBlitz 上创建了基本的 Angular 项目,并想添加我的组件。我右键单击 src 文件夹,Angular Generator > Component > test,它创建了带有测试组件的文件夹“test”。但是,当我尝试将此组件添加到 my-app 组件模板时,出现错误:
Error in src/main.ts (15:5)
'app-test' is not a known element:
1. If 'app-test' is an Angular component, then verify that it is included in the '@Component.imports' of this component.
2. If 'app-test' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@Component.schemas' of this component to suppress this message.
Run Code Online (Sandbox Code Playgroud)
如果我进一步添加导入,则会收到另一个错误:
Error in src/main.ts (10:27)
The component 'TestComponent' appears in 'imports', but is not standalone and cannot be imported directly. It must be imported via an NgModule.
Run Code Online (Sandbox Code Playgroud)
那么如何正确地将组件添加到我在 StackBlitz 上的 Angular 项目中呢?项目就在这里。
首先,请注意,使用独立组件并不是新的 Angular 15 默认设置。生成一个新的应用程序ng new
,您将找到所需的模块。您的麻烦根源在于 StackBlitz 决定以损害体验的方式更改他们的新应用程序模板。
使用独立组件实际上会使您在实际应用程序中的生活变得复杂,但我离题了。
您有两种选择来让您的 StackBlitz 应用程序正常运行。
首先,正如Harshit 的回答部分所示,您可以在整个过程中使用独立的组件。这是您需要的最少的更改,但随着组件列表的增加,它很快就会变得繁重。如果您打算将组件复制到您的应用程序中,则必须将其全部更改回来。无论如何,方法如下:
生成新组件后,将其添加standalone: true
到其@Component
装饰器中。
@Component({
standalone: true, <-- This is new
selector: 'my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css'],
})
export class MyComponent implements OnInit {
Run Code Online (Sandbox Code Playgroud)
然后,在每个使用 的组件中MyComponent
,将其添加到该组件的import
子句中:
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule, MyComponent], <-- This is changed
template: `
<h1>Hello from {{name}}!</h1>
<my-component></my-component>
`,
})
export class App {
Run Code Online (Sandbox Code Playgroud)
另一种方法是将新的 StackBlitz 应用程序转换为使用模块。这更好,但需要更多工作。
AppModule
.main.ts
为以下内容:import 'zone.js/dist/zone';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)
此时,StackBlitz 疯狂地告诉你:
NG0400:已创建具有不同配置的平台。
要摆脱它,您需要保存并重新加载页面。
app.module.ts
,导入新组件,引导它,然后导入BrowserModule
。简而言之,你的@NgModule
装饰器应该如下所示:@NgModule({
imports: [CommonModule, BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
Run Code Online (Sandbox Code Playgroud)
index.html
. 通常,那就是<my-app></my-app>
,因此您将选择器更改app.component.ts
为my-app
:@Component({
selector: 'my-app', <-- This is changed
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
Run Code Online (Sandbox Code Playgroud)
等等瞧!只需五个繁琐的步骤,您就可以将 StackBlitz 恢复到合理的默认值。如果您认为这很愚蠢,请在GitHub 问题上告知 StackBlitz 。
归档时间: |
|
查看次数: |
1936 次 |
最近记录: |