10

I need to label an upload button dynamically. My code so far:

<style>
   .file_upload_wrap.background_file:before {
    content: {{label}};  /* of course does not work */
  } 
</style>

<div class="file_upload_wrap background_file imgFormButton">
    <input type="file" class="file_upload" (change)="uploadFile($event, file)" name="file" id="file" [(ngModel)]="model.file"
      #file="ngModel">
</div>

How can I set the content dynamically?

3
  • Why are you writing js code in <style> tag? Commented Mar 26, 2018 at 11:53
  • this of course does not work. It should only illustrate what I want to do Commented Mar 26, 2018 at 11:54
  • a good question and I understand why u were just illustrating with this code, makes it clear what you are trying to do Commented Sep 29, 2023 at 11:09

3 Answers 3

17

You can use the attr css function to retrieve the value of an attribute

https://developer.mozilla.org/en-US/docs/Web/CSS/attr

component.css

.file_upload_wrap.background_file:before {
    content: attr(data-content);  
} 

component.html

<div class="file_upload_wrap background_file imgFormButton" [attr.data-content]="label">
    <input type="file" class="file_upload" (change)="uploadFile($event, file)" name="file" id="file" [(ngModel)]="model.file"
      #file="ngModel">
</div>

Edit: stackblitz showing example https://stackblitz.com/edit/angular-muysky?file=app%2Fapp.component.ts

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting method +1. I was just about to say you need to add it like [attr.data-content]="{{label}}". But then you added the edit :P
@John Yeah I realised that while I was actually testing on stackblitz :)
2

Instead of using css, and the :before selector, you could add an extra DOM-element before the div you want to decorate.

<label>{{label}}</label>
<div class="file_upload_wrap background_file imgFormButton">
        <input type="file" class="file_upload" (change)="uploadFile($event, file)" name="file" id="file" [(ngModel)]="model.file"
          #file="ngModel">
    </div>

Comments

0

Use a @HostBinding to defined CSS vars which you can then use in your .scss file, making it very easy to style :before and :after dynamically.

.ts:

size = 10
padding = 2

@HostBinding('attr.style')
public get cssVars() {
  return `
    --switch-size: ${this.size};
    --switch-padding: ${this.padding};
    --switch-size-inner: ${this.size - this.padding * 2};
  `;
}

.scss:

.my-class:before {
  height: calc(var(--switch-size) * 1px);
}

1 Comment

note - some people use DomSanitizer when using this approach but I didn't find it necessary (it worked without it) - see stackoverflow.com/a/64252610/1205871

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.