What is the best approach for connecting to a custom property in Angular 2?

Is there a better way to bind values to a non-native element attribute in Angular, as the usual approach doesn't seem to work as expected? Here is an example:

import {Directive, ElementRef, Input, OnInit, HostBinding} from 'angular2/core';

@Directive({
    selector: '[myFeet]'
})
export class MyFeetDirective {

    @HostBinding('feet')
    @Input() feetProps:string

    constructor(private el: ElementRef) { }
}

When using this directive:

<div [myFeet]="body.footCount"></div>

The desired result in the DOM after Angular rendering should be:

<div feet="2"></div>

I have achieved this by manually setting attributes in ngOnInit function:

ngOnInit(){
    this._setAttributes();
}

private _setAttributes(){
    if (this._feetProps != null) {
        this._el.nativeElement.setAttribute("feet", this._feetProps);
    }
}

Is there a more Angular-friendly way to accomplish this rather than directly manipulating the DOM? Your insights are appreciated.

Answer №1

To ensure the attribute is included in the DOM, opt for using attribute binding syntax rather than property binding syntax.

@Directive({
    selector: '[myFeet]'
})
export class MyFeetDirective {

    @HostBinding('attr.feet') 
    @Input() feetProps:string
}

Answer №2

To set the attribute using the value of the directive input, I would utilize the host block within the directive:

@Directive({
  selector: '[myFeet]',
  host: {
    '[attr.feet]': 'myFeetValue'
  }
})
export class MyFeetDirective {
  @Input('myFeet')
  myFeetValue:string
}

You can view an example on this plunkr: https://plnkr.co/edit/KYSIzmAqWLrc2n0yR8j5?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function doc.fromHTML is not recognized in Angular 6

I am having trouble exporting an HTML template to a PDF using the jsPDF library with Angular. I keep getting the error message "doc.fromHTML is not a function." import { Component, ViewChild, ElementRef } from '@angular/core'; import * as jsPDF ...

What could be causing my TypeScript object patch function to fail when passed empty patch objects?

Check out this TypeScript function I wrote, it's designed to apply a patch to an object where the patch is a partial object of the same type: function applyUpdate<T extends object>(obj: T, update: Readonly<Partial<T>>): T { const u ...

Can discriminated unions solely be utilized with literal types?

When looking at the code snippet below, I encountered an issue with discriminating the union type using the typeof operator. function f(arg: { status: number; one: boolean } | { status: string; two: boolean }) { if (typeof arg.status === "number&q ...

Revolutionizing Angular 8 with Hot Module Replacement

I have just embarked on a new Angular project and my goal is to incorporate HMR (Hot Module Replacement). Despite meticulously following the steps outlined in this guide, I continue to encounter the following errors: Utilizing the most recent version o ...

Exploring unnamed objects in JSON responses using RXJS in Angular 5

Currently, the situation is as follows: I am required to dynamically populate a mat-table after receiving a response from an API. Within the JSON response, there are anonymous JSON objects in the "files" array. "files": [ { "title": "dummy", ...

Exploring Ngu-Carousel in Angular 7: Importing JSON data for a dynamic display

After attempting to import data from JSON and display it using ngu-carousel, I encountered an error. The error shows "length of undefined" Subsequently, when I try to click on the previous/next button, another error appears. This error states "innerHTML ...

Is the validity of the expression !args.value || args.value.length true?

After analyzing this segment of code, I noticed an interesting expression: !args.value || args.value.length For instance, consider the following scenario: let v = {}; console.log(!v.value); //outputs true console.log(v.value); //outputs undefined con ...

Troubleshooting the display of API-generated lists in Angular 8

I am encountering an issue in Angular 8 when trying to display my list on a page. Below is the code from my proposal-component.ts file: import { Component, OnInit, Input } from "@angular/core"; import { ActivatedRoute, Params } from "@angular/router"; imp ...

The installation of Node on Ubuntu 18.04 encountered an error

Could someone assist me with this problem? I initially had node installed, then uninstalled it using the rm -rf command following online suggestions. Now I am trying to reinstall it using nvm install node However, I'm encountering the following error ...

Having trouble initializing TypeScript ReactApp. The error message reads: "Unable to locate the react-scripts command."

After creating a ReactApp using TypeScript, I encountered an issue when trying to start the server. Here are the steps I followed: $ npx create-react-app my-app --template typescript $ cd my-app $ npm start $ sh: react-scripts command not found I'm p ...

Is there a way for a TypeScript function to retrieve its own name similar to PHP's __FUNCTION__ magic constant?

Do Angular 2 and TypeScript have special constants? I dream of the following: ngOnInit() { console.log('__CURRENT_METHOD_NAME__ + has begun'); // displays ngOnInit has started running. } ...

"Zone has been successfully loaded" - incorporating angular universal ssr

I am currently working on an Angular project and I am looking to implement server-side rendering. To achieve this, I decided to use Angular Universal. The browser module of my project was successfully built, but I encountered the following issue during the ...

Tips for effective page management

After creating a navbar in my project, I've come to the realization that it requires a component for each page and subpage. This seems redundant especially when dealing with multiple navigation options like shown in this image. Is it necessary to crea ...

What is the best way to create an interface that only allows keys to be a combination of values from a specific property found within each object of an array?

interface Filter { id: string; name: string; } type Filters = Filter[]; const filters = [{ id: 'f1', name: 'f1name'}, { id: 'f2', name: 'f2name'}] interface State { ... } const state = { f1: any, ...

The function getStaticPaths() will generate a 404 error, indicating that the page

I have encountered a persistent issue with the getStaticPaths() function throwing a 404 error. After investigating, I suspect that the problem may lie in the implementation of the getAllPostIds() function, which is supposed to generate an array of object ...

Tips for activating strict null verification in Visual Studio Code

Typescript's strict null check feature is designed to prevent dynamic runtime errors, making it a valuable tool for developers. However, some may struggle to find clear instructions on how to enable it. Could someone provide guidance on enabling stri ...

Showcasing the information stored within my li element, I am able to access and view the data through my console

I want to showcase the data in the browser Upon hitting the api call, I retrieve the data in my console. The challenge lies in displaying the data within my li tag. Below are snippets of my relevant code and the entire code can be found in the gist links p ...

Accessing Angular2 form validation: receive a reference to ngForm

I'm trying to figure out how to have a reference to "myform" in the component. Is there a way to do this without using a formbuilder? I'd like to avoid that if possible. <form #myForm="ngForm"> <label class="col-sm-12" [class.ng-i ...

Encountering a configuration error in the Nginx.conf file while attempting to use

I recently obtained a Visual Studio solution that includes multiple projects. https://i.sstatic.net/HuRyl.jpg A Nginx.conf file was created in ClientApp/Angular. https://i.sstatic.net/CN65e.jpg This is my docker-compose file: clientapp: image: ${DOCKER ...

"Creating an Angular component that features a customizable global dynamic font in

I'm currently working on a feature that would allow users to change the font dynamically, which in turn should update the component accordingly. Since the component renders several material components with 'Roboto' styles, I've encount ...