gpt4 book ai didi

angular - 从代码中的 html 元素访问指令

转载 作者:太空狗 更新时间:2023-10-29 18:28:38 24 4
gpt4 key购买 nike

有没有办法通过代码从 HTMLElement 中检索自定义 @directive?

例如假设我已经声明了以下指令

@Directive({selector: '[appCustomDirective]'})
export class MyCustomDirective {
public MyVariable: string;
}

附加到按钮:

<button appCustomDirective>My button<button>

如果我将按钮作为 HTMLElement 变量,有没有办法:

  • 检查它是否附加了 appCustomDirective?
  • 检索指令的实例?

最佳答案

您应该能够通过您返回的元素上的注入(inject)器访问该指令。

组件:

@Component({
selector: 'app-my-custom-component',
template: `
<button id="with-directive" appMyCustomDirective>Click Me</button>
<button id="without-directive">Click Me Too</button>
`
})
export class MyCustomComponent {
}

指令:

@Directive({
selector: '[appMyCustomDirective]'
})
export class MyCustomDirective {
public myVariable = 'hello there!';
}

测试:

describe('MyCustomComponent', () => {
let component: MyCustomComponent;
let fixture: ComponentFixture<MyCustomComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyCustomComponent,
MyCustomDirective
]
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(MyCustomComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('displays a button with the directive', () => {
const buttonWithDirective = fixture.debugElement.query(By.css('#with-directive'));
const directiveInstance: MyCustomDirective = buttonWithDirective.injector.get(MyCustomDirective);
expect(directiveInstance.myVariable).toBe('hello there!');

const buttonWithoutDirective = fixture.debugElement.query(By.css('#without-directive'));
//danger!! this will throw an exception because there is no directive
//const directiveInstance: MyCustomDirective = buttonWithDirective.injector.get(MyCustomDirective);
});
});

关于angular - 从代码中的 html 元素访问指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52893452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com