如何以角度将值传递给指令 [英] How to pass values to directive in angular

查看:21
本文介绍了如何以角度将值传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码,

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

我的模型组件,

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


export class ModalComponent  {
  imageValue:any;

我想获取这个imageValue"的值,但我不知道该怎么做.任何人都可以帮助我.谢谢.

I want to get the value of this 'imageValue' but I dont know how to do it.Can anyone please help me.Thanks.

推荐答案

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

If you want to send data to directive then you should try like this:

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

This is my custom directive, and I am going to share two value from component or HTML to the directive.

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 中,如下所示:

and now your directive has been created and you will have add this directive into your app.module.ts like below:

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 .

I am sending name and value to the test.directive.ts .

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

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

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

Now see the console or use data in the directive accordingly.

这篇关于如何以角度将值传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆