如何在Angular 4中用*ng-if隐藏元素?及Angular @Input测试疑问
Angular 4 *ngIf使用及Jasmine@Input测试问题解答
嘿,我来帮你搞定这两个相关问题:如何用*ngIf隐藏元素,以及修复你Jasmine测试里的bug!
一、用*ngIf在Angular 4中控制元素显示/隐藏
*ngIf是Angular里用来完全添加/移除DOM元素的指令(不是简单的样式隐藏),用法超直观:
- 先在组件类里定义控制条件(就是你已经写的
enable属性,注意补个分号哦):
import { Component, Input } from '@angular/core'; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: [ "./app.component.css" ] }) export class AppComponent { name = "Angular 4"; @Input() enable: boolean; constructor() { } }
- 在模板里把
*ngIf绑定到这个属性,控制p标签的显示:
<!-- enable为true时渲染p标签,false时直接从DOM里删掉 --> <p *ngIf="enable">这里是要控制显示的内容</p>
这样当enable设为false时,p标签就彻底从页面里消失啦,不是单纯靠样式躲起来哦。
二、修复你的Jasmine测试代码
你的测试逻辑有几个小问题,导致没法正确验证p标签的状态:
- 当
enable为false时,query(By.css('p'))会返回null,这时候直接访问nativeElement会报错 - 你错误地用了
nativeElement.length——单个DOM元素根本没有这个属性,只有查询多个元素的queryAll()返回的数组才有
修正后的完整测试代码:
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { AppComponent } from './app.component'; describe('@Input property tests', () => { let component: AppComponent; let fixture: ComponentFixture<AppComponent>; // 每个测试前初始化组件,保证测试独立性 beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ AppComponent ] }).compileComponents(); fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; }); it('should NOT render p tag when enable is false', () => { component.enable = false; fixture.detectChanges(); // 触发变更检测,更新DOM const pElement = fixture.debugElement.query(By.css('p')); // 直接断言元素不存在 expect(pElement).toBeNull(); }); it('should render p tag when enable is true', () => { component.enable = true; fixture.detectChanges(); const pElement = fixture.debugElement.query(By.css('p')); // 断言元素存在,还可以顺便验证内容 expect(pElement).not.toBeNull(); expect(pElement.nativeElement.textContent.trim()).toBe('这里是要控制显示的内容'); }); });
几个关键提醒:
- 一定要在
beforeEach里初始化组件和fixture,确保每个测试用例都是独立的干净环境 - 当元素被
*ngIf移除时,query()会返回null,直接断言这个就够了 - 如果要查询多个同类型元素,用
queryAll(),这时候可以用返回数组的length来判断数量
内容的提问来源于stack exchange,提问作者user944513
相关产品推荐
相关产品推荐

