How do I add a html template to a directive? Here is a sample code which does not work :
import { Directive } from '@angular/core';
@Directive({
selector: '[master-side-bar]',
templateUrl : 'master-side-bar.html' })export class MasterSideBar {
constructor() {
console.log('Hello MasterSideBar Directive');
}
}
I get the following error :
Argument of type '{ selector: string; templateUrl: string; }' is not assignable to parameter of type 'Directive'. Object literal may only specify known properties, and 'templateUrl' does not exist in type 'Directive'.
When to use templateUrl in Angular applications? When you have a complex view, then it recommended by Angular to create that complex view in an external HTML file instead of an inline template. The Angular component decorator provides a property called templateUrl. This property takes the path of an external HTML file.
According to Angular docs there are 2 types of directives: attribute and structural. None of them support templates.
We're prefixing these directive names with an asterisk (*). The asterisk is "syntactic sugar". It simplifies ngIf and ngFor for both the writer and the reader. Under the hood, Angular replaces the asterisk version with a more verbose form.
Naming Convention: *[name of directive] — Upper camel case is used for the directive class, while lower camel case is used for the directive's name. What sets them apart from other directives in Angular 2: Reshape DOM structure by adding or removing existing DOM elements and do not have templates.
From your code, you need to use component not directives.
Component is the only directive which accepts template as HTML.
Please check Types of directives
Hope it helps!!
According to Angular docs there are 2 types of directives: attribute and structural. None of them support templates. Just use angular Component. Is there some good reason that you want to use directive necessarily?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With