Angular 17旧应用启用Hydration:如何跳过路由加载模块的水合?
在Angular 17中跳过路由加载模块的水合处理及ESLint问题解决
一、跳过路由模块的水合
对于<router-outlet>加载的模块,只要给模块的根组件设置ngSkipHydration,就能让整个模块跳过水合(水合规则会顺着组件树向下继承)。这里有两种合规的实现方式:
方法1:用@HostBinding(推荐,避开ESLint报错)
直接在模块根组件的类中添加@HostBinding绑定ngSkipHydration属性:
import { Component, HostBinding } from '@angular/core'; @Component({ selector: 'app-your-module-root', templateUrl: './your-module-root.component.html', styleUrls: ['./your-module-root.component.css'] }) export class YourModuleRootComponent { @HostBinding('ngSkipHydration') skipHydration = true; }
方法2:在模板根元素添加属性
如果不想修改组件类,直接在组件模板的最外层标签上添加ngSkipHydration="true"即可:
<div ngSkipHydration="true"> <!-- 模块内所有内容都包裹在这个容器中 --> </div>
二、解决ESLint的no-host-metadata-property错误
你遇到的错误是因为Angular ESLint规则禁止在@Component元数据中使用host属性,官方现在推荐用@HostBinding/@HostListener替代旧的host配置。
如果特殊场景下必须使用host元数据,可以临时禁用这段代码的ESLint规则(不推荐,仅作应急方案):
/* eslint-disable @angular-eslint/no-host-metadata-property */ import { Component } from '@angular/core'; @Component({ selector: 'app-your-module-root', templateUrl: './your-module-root.component.html', styleUrls: ['./your-module-root.component.css'], host: { ngSkipHydration: 'true' } }) export class YourModuleRootComponent {} /* eslint-enable @angular-eslint/no-host-metadata-property */
更建议采用@HostBinding的实现方式,既符合Angular最佳实践,也无需修改ESLint配置。
内容的提问来源于stack exchange,提问作者Catherine Clague
相关产品推荐
相关产品推荐

