简体   繁体   English

如何以角度创建自定义指令

[英]How to create a custom directive in angular

i have been writing an application in angular and i am getting to grips with most stuff pretty well.我一直在用 angular 编写一个应用程序,并且我已经很好地掌握了大多数东西。 One thing i don't understand is structural directives or anything that uses code changes the DOM我不明白的一件事是结构指令或任何使用代码更改 DOM 的东西

For the simplest example of what I'm looking to learn, in a parent template if i have对于我想要学习的最简单的例子,如果我有的话,在父模板中

<div [addTitle]='sometitle'>
   <child-component></child-component>
</div>

i want to build a directive that when i add a div with [addTitle]='sometitle' attribute it alters the final code to this我想构建一个指令,当我添加一个带有 [addTitle]='sometitle' 属性的 div 时,它会将最终代码更改为此

<div [addTitle]='sometitle'>
   <h2>sometitle</h2>
   <child-component></child-component>
</div>

whilst keeping the content of <child-component></child-component> unaltered and with all the bindings within intact etc.同时保持<child-component></child-component>不变,并且所有绑定都完好无损等。

i know i need a file such as我知道我需要一个文件,例如

import { Directive, Input } from '@angular/core';

@Directive({
  selector: '[addTitle]'
})
export class addTitleDirective {
  constructor() { }
}

i just don't known how to access the inner 'html' of the tag with the directive on it or keep the child-component from being destroyed or how to add the <h2>sometitle</h2> to the DOM or show the html that is inside the <child-component> back to the DOM我只是不知道如何访问带有指令的标签的内部“html”或防止子组件被破坏或如何将<h2>sometitle</h2>到 DOM 或显示将<child-component>内的 html 返回到 DOM

im sorry if this is to general but i am looking for some pointers to help me get started.对不起,如果这是一般的,但我正在寻找一些指导来帮助我开始。

edit inorganik has kindly pointed out that a component is more suited and given example ..thank you.编辑inorganik 善意地指出组件更适合并给出示例..谢谢。

i was wondering if i had我想知道我有没有

<div [addTitles]="['sometitle1', 'sometitle2']">
   <child-component1></child-component1>
   <child-component2></child-component2>
</div>

and wanted to end up with并想结束

<div [addTitle]="['sometitle1', 'sometitle2']">

   <h2>sometitle1</h2>
   <child-component1></child-component1>

   <h2>sometitle2</h2>
   <child-component2></child-component2>

</div>

would a component still work?一个组件还能工作吗?

I believe you are looking for ng-content .我相信您正在寻找ng-content Also I think your example would be better served by a component than directive - So your component might look like this:此外,我认为组件比指令更好地为您的示例提供服务 - 因此您的组件可能如下所示:

@Component({
  selector: 'app-title',
  templateUrl: './title.component.html',
  styleUrls: ['./title.component.scss'],
})
export class TitleComponent {

  @Input() addTitle: string;

}

template:模板:

<h2>{{ addTitle }}</h2>
<ng-content></ng-content>

Then you use it like this:然后你像这样使用它:

<app-title [addTitle]="'my title'">
  <child-component></childcomponent>
</app-title>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM