angular - 如何将值传递给 Angular Directive(指令)

标签 angular typescript angular-directive

我的代码,

  <modal *ngIf='showModal' [imageValue]="imageId"></modal>

我的模型组件,

@Component({
  selector: 'modal',
  templateUrl: './app/modal/modal.component.html',
  providers: [HeaderClass]
})


export class ModalComponent  {
  imageValue:any;

我想获取这个“imageValue”的值,但我不知道该怎么做。谁能帮帮我。谢谢。

最佳答案

如果你想向指令发送数据,那么你应该这样尝试:

这是我的自定义指令,我将把组件或 HTML 中的两个值共享给该指令。

test.directive.ts:

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

@Directive({
    selector: '[input-box]'
})

export class TestDirectives implements OnInit {
    @Input() name: string;
    @Input() value: string;
    constructor(private elementRef: ElementRef) {
    }
    ngOnInit() {
        console.log("input-box keys  : ", this.name, this.value);
    }
}

现在你的指令已经创建,你将把这个指令添加到你的 app.module.ts 中,如下所示:

app.module.ts:

import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { TestDirectives } from '../directives/test.directive';


@NgModule({
  declarations: [
    AppComponent,
    TestDirectives
  ],
  imports: [],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

您必须在 html 中使用您的指令并将数据发送到指令,如下面的代码所示。

我正在将 namevalue 发送到 test.directive.ts

<div input-box [name]="'lightcyan'" [value]="'CYAN'"></div>

<div input-box [name]="componentObject.name" [value]="componentObject.value"></div>

现在查看控制台或相应地在指令中使用数据。

关于angular - 如何将值传递给 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124998/

相关文章:

angular - IntelliJ IDEA 显示 matHeaderRowDef 错误

javascript - 纠正 angularJS 中的用户输入

javascript - TypeScript 中的泛型有何用处

angular - HostBinding 到匿名 lambda 函数?

angular - *ngIf 不对 bool 值变化使用react

javascript - 删除搜索结果/angular2/typescript/js 中的重复值

typescript - Vue Prop 没有初始化器,在构造函数中没有明确赋值

angular - 如何在 Angular 2 中添加 TinyMce?

angular - Ionic和Angular中如何知道每个http请求的请求进度

angular - 有没有办法使用 ngx bootstrap 获取事件选项卡?