溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Angular的獨立組件怎么使用

發(fā)布時間:2022-08-05 10:49:03 來源:億速云 閱讀:144 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Angular的獨立組件怎么使用”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強(qiáng),希望這篇“Angular的獨立組件怎么使用”文章能幫助大家解決問題。

如何創(chuàng)建一個獨立組件

對于已有的組件,我們可以在@Component()中添加standalone: true的標(biāo)識,然后我們可以在沒有@NgModule()的情況下直接使用imports導(dǎo)入其他模塊了。
如果是新建組件,可以使用ng generate component <name> --standalone的命令,直接創(chuàng)建一個獨立組件, 例如:

ng generate component button-list --standalone
@Component({
  selector: 'app-button-list',
  standalone: true,
  imports: [
    CommonModule,
  ],
  templateUrl: './button-list.component.html',
  styleUrls: ['./button-list.component.scss']
})
export class ButtonListComponent implements OnInit

在獨立組件中導(dǎo)入已有的模塊

我們可以在imports中添加已有的模塊,以MatButtonModule為例:

imports: [
    CommonModule,
    MatButtonModule,
],

這樣子我們就可以在ButtonListComponent中使用MatButtonModulemat-button組件了:

<button mat-button>Basic</button>
<button mat-button color="primary">Primary</button>
<button mat-button color="accent">Accent</button>
<button mat-button color="warn">Warn</button>
<button mat-button disabled>Disabled</button>
<a mat-button href="https://damingerdai.github.io" rel="external nofollow"  target="_blank">Link</a>

效果圖:

Angular的獨立組件怎么使用

使用獨立組件啟動Angular應(yīng)用

第一步, 將AppComponent設(shè)置為獨立組件:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  standalone: true,
})
export class AppComponent {
    ...
}

第二步,將AppModule的imports中的導(dǎo)入的模塊加入到AppComponent的imports中,但是有兩個模塊例外: BrowserModuleBrowserAnimationsModule。

如果導(dǎo)入的話,可能會導(dǎo)致** BrowserModule have already been loaded. If you need access to common directives such as NgIf and NgFor, import the CommonModule instead.**的問題:

Angular的獨立組件怎么使用

第三步,刪除app.module.ts文件

最后一步, 將main.ts中的:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

改為:

bootstrapApplication(AppComponent).catch(err => console.error(err));

這樣子我們就實現(xiàn)了使用獨立組件啟動Angular組件了。

為獨立組件配置路由

我這里分別有三個獨立組件: HomeComponent, ButtonListComponentChipListComponent,

然后在main.ts中創(chuàng)建ROUTES對象

const ROUTES: Route[] = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'home'
  },
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'button',
    loadComponent: () =>
      import('./app/button-list/button-list.component').then(
        (mod) => mod.ButtonListComponent
      ),
  },
  {
    path: 'chip',
    loadComponent: () =>
      import('./app/chip-list/chip-list.component').then(
        (mod) => mod.ChipListComponent
      ),
  },
];

其中ButtonListComponentChipListComponent使用loadComponent去實現(xiàn)路由懶加載。

最后在bootstrapApplication的第二個參數(shù)中使用providers注冊RouterModule好了。

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(RouterModule.forRoot([...ROUTES])),
  ],
}).catch(err => console.error(err));

效果圖:

Angular的獨立組件怎么使用

配置依賴注入

當(dāng)我們想要啟動Angular應(yīng)用的時候,可能需要注入一些值或者服務(wù)。 在bootstrapApplication, 我們可以通過providers來注冊值或者服務(wù)。

比如,我有一個獲取圖片的url,需要注入到PhotoService中:

bootstrapApplication(AppComponent, {
  providers: [
    {
      provide: 'photoUrl',
      useValue: 'https://picsum.photos',
    },
    {provide: PhotosService, useClass: PhotosService },
    importProvidersFrom(RouterModule.forRoot([...ROUTES])),
    importProvidersFrom(HttpClientModule)
  ],
})

PhotoService代碼如下:

@Injectable()
export class PhotosService {

  constructor(
    @Inject('photoUrl') private photoUrl: string,
    private http: HttpClient
  ) { }

  public getPhotoUrl(i: number): string {
    return `${this.photoUrl}/200/300?random=${i}`;
  }
}

關(guān)于“Angular的獨立組件怎么使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI