Gaurav_0093
Gaurav_0093

Reputation: 1030

how to use scope in angular directive 4

Hello All I am using angular directive 1.6 to access ate attributes of a numeric textbox control here is my directive

app.directive('numerictextbox', function () {
    return {
        restrict: 'EA',
        require: 'ngModel',
        replace: true,
        template: '<input type="number" />',

        scope: {
            id: '@',
            ngModel: '=',
            min: '@',
            max: '@'
        },
        link: function (scope, element) {

            element.on('change', function () {
                scope.ngModel
                scope.$applyAsync();

            })
        }

    };

and here is my control

<numerictextbox id="txtid2" min="1" max="4" ng-model="txt2"></numerictextbox>

so the question is how can get the control attributes value in angular directive here is my angular 4 directive

@Directive({
        selector: '[number]'

})

how we can use scope in angular 4 directive anybody please help

Upvotes: 0

Views: 157

Answers (1)

swetansh kumar
swetansh kumar

Reputation: 475

Add properties into the Directive class with @Input() decorator

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

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

    ...
}

And in the template pass bound properties to your li element

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

I have implemented in this way.This is working fine in my project.Please try it.

Upvotes: 1

Related Questions