Как передать несколько параметров в @ Directives в Angular с помощью TypeScript?

так как я создал @Directive as SelectableDirective, Я немного запутался, о том, как пройти более одного значение для пользовательской директивы. Я искал много, но не получил правильного решения в Угловое С машинопись.

вот мой пример кода:

родительский компонент, как MCQComponent:

import { Component, OnInit } from '@angular/core';
import { Question } from '../question/question';
import { AppService } from '../app.service/app.service';
import { SelectableDirective } from '../selectable.directive/selectable.directive';
import { ResultComponent } from '../result-component/result.component';

@Component({
    selector: 'mcq-component',
    template: "
         .....
        <div *ngIf = 'isQuestionView'>
            <ul>
                <li *ngFor = 'let opt of currentQuestion.options' 
                    [selectable] = 'opt'
                    (selectedOption) = 'onOptionSelection($event)'>
                    {{opt.option}}
                </li>
            </ul>
            .....
        </div>

    "
    providers: [AppService],
    directives: [SelectableDirective, ResultComponent]
})
export class MCQComponent implements OnInit{
    private currentIndex:any = 0;
    private currentQuestion:Question = new Question();
    private questionList:Array<Question> = [];
    ....
    constructor(private appService: AppService){}
    ....
}

это родительский компонент, имеющий пользовательскую директиву [выбор], который принимает один параметр называется opt.

вот код для этой директивы:

import { Directive, HostListener, ElementRef, Input, Output, EventEmitter } from '@angular/core'
import { Question } from '../question/question';

@Directive({
    selector: '[selectable]'
})
export class SelectableDirective{
    private el: HTMLElement;
    @Input('selectable') option:any;

    ...
}

так вот я хочу передать дополнительные параметры от родительского элемента компонент, как мне этого достичь?

3 ответов


С документация

как и с компонентами, вы можете добавить столько Привязок свойств директивы, сколько вам нужно, нанизывая их вдоль в шаблоне.

добавить свойство ввода в HighlightDirective под названием defaultColor:

@Input() defaultColor: string;

разметки

<p [myHighlight]="color" defaultColor="violet">
  Highlight me too!
</p>

Угловое знает, что defaultColor привязка принадлежит HighlightDirective потому что вы сделали это публичным с @Input оформитель.

в любом случае @Input декоратор сообщает Angular, что это свойство общедоступный и доступный для привязки родительским компонентом. Без @Input, Angular отказывается привязываться к свойству.

со многими параметрами

добавить свойства в Directive класс @Input() оформителя

@Directive({
    selector: '[selectable]'
})
export class SelectableDirective{
    private el: HTMLElement;

    @Input('selectable') option:any;   
    @Input('first') f;
    @Input('second') s;

    ...
}

и в шаблон передать свойства привязки к вашему li элемент

<li *ngFor = 'let opt of currentQuestion.options' 
    [selectable] = 'opt' 
    [first]='YourParameterHere'
    [second]='YourParameterHere'
    (selectedOption) = 'onOptionSelection($event)'>
    {{opt.option}}
</li>

здесь li элемент у нас есть директива с именем selectable. В selectable у нас есть два @Input() ' s,f С именем first и s С именем second. Мы применили эти два на li свойства с именем [first] и [second]. И наша директива найдет эти свойства на этом li элемент, которые установлены для него с @Input() оформителя. Так что selectable, [first] и [second] будет привязан к каждой директивы li, который имеет свойство с этими именами.

С одним параметром

@Directive({
    selector: '[selectable]'
})
export class SelectableDirective{
    private el: HTMLElement;

    @Input('selectable') option:any;   
    @Input('params') params;

    ...
}

разметки

<li *ngFor = 'let opt of currentQuestion.options' 
    [selectable] = 'opt' 
    [params]='{firstParam: 1, seconParam: 2, thirdParam: 3}'
    (selectedOption) = 'onOptionSelection($event)'>
    {{opt.option}}
</li>

чтобы передать много опций, вы можете передать объект декоратору @Input с пользовательскими данными в одной строке.

в шаблоне

<li *ngFor = 'let opt of currentQuestion.options' 
                [selectable] = 'opt'
                [myOptions] ="{first: opt.val1, second: opt.val2}" // these are your multiple parameters
                (selectedOption) = 'onOptionSelection($event)' >
     {{opt.option}}
</li>

Итак, в директивном классе

@Directive({
  selector: '[selectable]'
})

export class SelectableDirective{
  private el: HTMLElement;
  @Input('selectable') option:any;
  @Input('myOptions') data;

  //do something with data.first
  ...
  // do something with data.second
}

еще один удобный вариант-использовать Directive как элемент, а не как атрибут.

@Directive({
   selector: 'app-directive'
})
export class InformativeDirective implements AfterViewInit {

    @Input()
    public first: string;

    @Input()
    public second: string;

    ngAfterViewInit(): void {
       console.log(`Values: ${this.first}, ${this.second}`);
    }
}

и эту директиву можно использовать так:

<app-someKindOfComponent>
    <app-directive [first]="'first 1'" [second]="'second 1'">A</app-directive>
    <app-directive [first]="'First 2'" [second]="'second 2'">B</app-directive>
    <app-directive [first]="'First 3'" [second]="'second 3'">C</app-directive>
</app-someKindOfComponent>`

простой, аккуратный и мощный.