Render2 无法在 Angular 基本项目中工作

问题描述 投票:0回答:1

我有一个角度应用程序 Angular-tour-of-heroes ,其结构如下:

src
   ->app
         ->your-component
                  ->your-component.component.html
                  ->your-component.component.less
                  ->your-component.component.ts
                  ->default.less
                  ->custom.less
         ->app.component.html
         ->app.component.ts
         ->app.module.ts
         ->app-routing.module.ts
         ->style-manager.service.ts

现在我将分享文件:

app.component.html

<app-your-component></app-your-component>

app.module.ts

// src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { YourComponent } from './your-component/your-component.component';
@NgModule({
  declarations: [
    AppComponent,
    YourComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

angular.json

{
"styles": [
"src/styles.less",
"src/app/your-component/default.less",
"src/app/your-component/custom.less"]
}

样式管理器.service.ts

// src/app/common_modules/common_services/style-manager.service.ts
import { Injectable, Renderer2, RendererFactory2 } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class StyleManagerService {
  private renderer: Renderer2;
  private addedStylesheets: HTMLLinkElement[] = [];
  constructor(rendererFactory: RendererFactory2) {
    this.renderer = rendererFactory.createRenderer(null, null);
  }
  addStylesheets(links: string[]) {
    links.forEach(link => {
      const styleLink = this.renderer.createElement('link');
      this.renderer.setAttribute(styleLink, 'rel', 'stylesheet');
      this.renderer.setAttribute(styleLink, 'type', 'text/css');
      this.renderer.setAttribute(styleLink, 'href', 'custom.less');
      this.renderer.setAttribute(styleLink, 'app-dynamic-style', 'true');
      this.renderer.appendChild(document.head, styleLink);
      this.addedStylesheets.push(styleLink);
    });
  }
  removeStylesheets() {
    // Remove all dynamically added style elements
    this.addedStylesheets.forEach(link => {
      this.renderer.removeChild(document.head, link);
    });
    this.addedStylesheets = [];
  }
}

您的组件.component.ts

// src/app/your-component/your-component.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StyleManagerService } from '../style-manager.service';
@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./default.less'] // Use default styles by default
})
export class YourComponent implements OnInit, OnDestroy {
  constructor(private styleManager: StyleManagerService) {}
  ngOnInit() {
    // Some condition to determine which Less file to load
    const condition = true; // Change this condition as needed
    if (condition) {
      // Load custom Less file
      this.styleManager.addStylesheets(['./your-component/custom.less']);
    }
  }
ngOnDestroy() {
    // Remove dynamically added stylesheets when the component is destroyed
    this.styleManager.removeStylesheets();
  }
}

您的组件.html

<p>your-component works!</p>

默认.less

p{
    color: aqua;
}

自定义。更少

p{
    color: yellow;
}

我尝试了上面的代码,并发布了当我执行服务时,我收到了 custom.less 文件的 404 错误。 有人可以帮我看看我做错了什么以及哪里做错了吗

css angular angularjs render servicemanager
1个回答
0
投票

您可以将CSS文件放在assets文件夹中,然后代码就可以正常工作,请在下面找到一个工作示例!

html

<select [(ngModel)]="style" (ngModelChange)="setStyleSheet()">
  <option [value]="'../assets/qwerty.css'">qwerty</option>
  <option [value]="'../assets/custom.css'">custom</option>
  <option [value]="'../assets/zxcv.css'">zxcv</option>
</select>
<p class="test">your-component works!</p>

ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { StyleManagerService } from '../style-manager.service';
@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  standalone: true,
  imports: [FormsModule],
  styleUrls: ['../assets/default.css'], // Use default styles by default
})
export class YourComponent implements OnInit, OnDestroy {
  style = '../assets/default.css';
  constructor(private styleManager: StyleManagerService) {}
  ngOnInit() {}

  setStyleSheet() {
    if (this.style) {
      // Load custom Less file
      this.styleManager.addStylesheets([this.style]);
    }
  }

  ngOnDestroy() {
    // Remove dynamically added stylesheets when the component is destroyed
    this.styleManager.removeStylesheets();
  }
}

服务

// src/app/common_modules/common_services/style-manager.service.ts
import { Injectable, Renderer2, RendererFactory2 } from '@angular/core';
@Injectable({
  providedIn: 'root',
})
export class StyleManagerService {
  private renderer: Renderer2;
  private addedStylesheets: HTMLLinkElement[] = [];
  constructor(rendererFactory: RendererFactory2) {
    this.renderer = rendererFactory.createRenderer(null, null);
  }
  addStylesheets(links: string[]) {
    links.forEach((link) => {
      if (this.addStylesheets.length) {
        this.addedStylesheets.forEach((link: any) => {
          this.renderer.removeChild(document.head, link);
        });
        this.addedStylesheets = [];
      }
      const styleLink = this.renderer.createElement('link');
      this.renderer.setAttribute(styleLink, 'rel', 'stylesheet');
      this.renderer.setAttribute(styleLink, 'type', 'text/css');
      this.renderer.setAttribute(styleLink, 'href', link);
      this.renderer.setAttribute(styleLink, 'app-dynamic-style', 'true');
      this.renderer.appendChild(document.head, styleLink);
      this.addedStylesheets.push(styleLink);
    });
  }
  removeStylesheets() {
    // Remove all dynamically added style elements
    this.addedStylesheets.forEach((link) => {
      this.renderer.removeChild(document.head, link);
    });
    this.addedStylesheets = [];
  }
}

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.