Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use templateUrl in Angular 2 directive

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'.

like image 694
max Avatar asked May 27 '17 17:05

max


People also ask

What is templateUrl in Angular?

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.

Can directives have template in Angular?

According to Angular docs there are 2 types of directives: attribute and structural. None of them support templates.

Why We Use * Before NgIf?

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.

What is the naming convention of built in directives in angular 2?

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.


2 Answers

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!!

like image 76
Jayakrishnan Avatar answered Jan 03 '23 07:01

Jayakrishnan


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?

like image 36
tomeks Avatar answered Jan 03 '23 06:01

tomeks