Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use directive in host of another Directive

I want to add a directive to an element from another directive by using the host property, but there doesn't seem to be a way to reference the other directive.

@Directive({
    selector: '[one]',
    host: { '[two]': '"some-value"' }
    // How can I reference DirectiveTwo here?
})
export class DirectiveOne { }

@Directive({
    selector: '[two]'
})
export class DirectiveTwo { }

When doing this, I get the standard "Can't bind to 'two' since it isn't a known native property" error.

What is the correct way of referencing and using one directive from another?

like image 724
Yona Appletree Avatar asked May 10 '16 20:05

Yona Appletree


People also ask

Can we use multiple directives in Angular?

You can not use two structural directives on the same element. You need to wrap your element in another one. It's advised to use ng-container since it wont be rendered in DOM.

How do I pass data from one directive to another directive in AngularJS?

The best way to pass an object to an angular directive is by using the &. When you use &, angular compiles the string as an expression and sets the scope variable in your directive to a function that, when called, will evaluate the expression in the context of the directive's parent's scope.

Can a directive have input?

If we also specify an input property in our directive's class using the same value as the selector property value we can input data into our directive using the attribute on the host element. This instructs Angular that the appBtnGrow class member property is now an input that can receive a value from the host element.

What is @directive in Angular?

What is meant by directives in Angular? Directives are classes that add new behavior or modify the existing behavior to the elements in the template. Basically directives are used to manipulate the DOM, for example adding/removing the element from DOM or changing the appearance of the DOM elements.


1 Answers

Directives are instantiated by Angular for selectors matching statically added HTML (element, id, attribute, class, ...) only.
There is no way to instantiate directives using the host parameter of the @Component() or @Directive() decorator. There is also no way to create directives dynamically using ViewContainerRef.createComponent() (former DynamicComponentLoader)

Getting a reference to another directive that was instantiated by Angular because of a statically added HTML on the same element is supported though.

like image 95
Günter Zöchbauer Avatar answered Oct 12 '22 05:10

Günter Zöchbauer