typescript 如何在Angular 17中使用选择器显示组件

dzhpxtsq  于 7个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(64)

现在我正在使用Angular 17(Angular CLI:17.0.0)。
目录的结构如下:

/src
    /app
        /x
            x.component.css
            x.component.html
            x.component.spec.ts
            x.component.ts
        app.component.css
        app.component.html
        app.component.spec.ts
        app.component.ts
        app.config.ts
        app.routes.ts
    /assets
    favicon.ico
    index.html
    main.ts
    styles.css

字符串
我想通过将<app-x></app-x>添加到app.component.html并在app.component.ts中导入x来包含我的组件x的内容。但是该组件的内容不会显示在应用程序中。
我做错了什么?

laawzig2

laawzig21#

您需要导入在x.component.ts中定义的组件类

export class XComponent {

}

字符串
然后在app.component.ts上添加imports数组

@Component({
  ...
  imports: [CommonModule, RouterOutlet, XComponent],
  ...
})

rjjhvcjd

rjjhvcjd2#

请确保您的x.component.ts和x.component.html文件包含有效的代码和模板。不应存在语法错误或阻止显示内容的问题。
下面是一个如何在app组件中包含x组件的示例:

// app.component.ts
    import { Component } from '@angular/core';
    import { XComponent } from './x/x.component'; // Check the path to the XComponent file
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      // Any necessary logic for the app component
    }

字符串
//app.component.html

<div>
      <!-- Other content or components -->
      <app-x></app-x> <!-- Include the XComponent here -->
    </div>

相关问题