Using angular to create an external hyperlink - my inability to access external pages is frustrating

Here's the question at hand:

How can I make links in HTML or TypeScript work properly? I want to include links to external pages within my app. In a user profile, I have links to the social media accounts of that user (e.g. instagram.com/sisterofclara) displayed as follows:

<div class="col-md-12"  *ngFor="let currentAccountObject of user.userContact.accounts">
   <div class="margin-10-px" >
       <div class="col-md-1 font-bold"> 
          <img[src]="getIcon(currentAccountObject.socialAccountType)">
       </div>
       <div class="col-md-9 font-bold"> {{currentAccountObject.login}}
       </div>
   </div>
</div>

However, every time I click on a link, it always redirects to `localhost:3000` before the actual link. Why is this happening?

I've tried using an Angular click function with the argument `uri`, like so:

 public goToProfile(url) {
    window.location.href = url;
  }

I've attempted various methods such as clicking directly on the link, using `href={{person.link}}`, the provided function, and even location.replace(uri), but none seem to be working correctly due to the addition of `localhost` at the beginning of the URL. Any insights on this issue?

Edit: Here's the corresponding HTML code snippet:

 <div class="row col-md-12 contact">
            <div *ngIf="contactTabEditable==false">
              <div class="col-md-12 ro-label" align="left">Social media:</div>
              <div class="col-md-10 social-media">
                <div>
                  <div class="col-md-12"  *ngFor="let currentAccountObject of user.userContact.accounts">
                      <div class="margin-10-px" >
                          <div class="col-md-1 font-bold"><img [src]="getIcon(currentAccountObject.socialAccountType)"></div>
                          <div *ngIf="currentAccountObject.link" class="col-md-9 font-bold"> 
                            <a (click)="goToProfile(currentAccountObject.link)"> {{currentAccountObject.login}} </a>
                          </div>
                          <!-- <div *ngIf="!showClickableAccount" class="col-md-9 font-bold"> {{currentAccountObject.login}}</div> -->
                      </div>
                 </div>
                </div>
              </div>

            </div>
          </div>


Answer №1

To easily create a link to an external website, you can just use an <a href="externalUrl"> tag.
If you prefer to use data binding to dynamically bind the link in your element, you can do it like this:

<a [attr.href]="url"></a>

If you have a variable named url in your component:

public url = "https://google.com/";

Another option would be:

<a href="{{url}}">URL</a>

Or if you have a field for the user's Instagram name:
Taken from official documentation:

<a [href]="'https://www.instagram.com/' + user.instagramName">Instagram Profile</a>

Answer №2

I managed to resolve the issue by utilizing the code snippet provided below:

Hopefully, this solution proves beneficial for you as well.

To address the problem, simply replace your existing function with the following code:

public goToProfile(url: string) {
        let u: string = '';
        if (!/^http[s]?:\/\//.test(url)) {
          u += 'http://';
        }
        u += url;
        let link = this.document.createElement("a");
        link.target = '_blank';
        link.href = u;
        link.setAttribute('visibility', 'hidden');
        link.click();
    }

Don't forget to include the document in your constructor:

constructor(@Inject(DOCUMENT) private document: any){}

Also, make sure to import DOCUMENT like so:

import { DOCUMENT } from '@angular/platform-browser';

If you require further assistance, feel free to reach out.

Thank you!

Answer №3

Feel free to give this code a shot. Wishing you success.

<a href="url_of_website" target="”_blank”" rel="noopener noreferrer">Click Here</a>

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

Angular binding of variable names beginning with numbers

Currently in my Angular 4 project, I am utilizing the interpolation syntax below: {{variable.24h_volume}} Upon implementation, an error is thrown stating: Unexpected token '0.24' at column 5 in [{{variable.24h_volume}}] in ng:///AppModule/Comp ...

What impact does the size of the unpacked files have on the overall minified size of an npm package?

I've been working on shrinking the size of an npm package I created, and I've successfully reduced the unpacked size to around 210kb. https://www.npmjs.com/package/@agile-ts/core/v/0.0.12 <- 210kb https://www.npmjs.com/package/@agile-ts/core ...

Clearing the text field after submitting the content

I am trying to remove the content of a text field after adding an option into a select list. Here is an example of the HTML code: <select size="15" style="width:230px" style="text-align:right" id="theaterSelectControl"> <option>111</opt ...

What is the best way to display multiple files in a vertical stack when choosing a file?

<div class="selected-file-container align-items-center justify-content-between d-none"> <div class="selected-file d-flex align-items-center"> <img id="selectedImage" class="hidden" src="&qu ...

Challenges with Scalable Vector Graphics and Responsiveness

I'm experiencing an issue with my home page at While the map displays correctly on larger screens, I want to enhance its flexibility so that it resizes automatically when I decrease the size of my browser window. How can I achieve this? My code is q ...

Using jQuery to smoothly scroll to a specific class name

I am faced with an HTML code snippet that looks like this: <div data-stored="storenow" data-save="save" class="saveIcon" data-unique="game">Save</div> My intention is to use jQuery to scroll to the game number 456 as shown below. var contain ...

Anticipating the loading of the next page in JavaScript

Can I use JavaScript to open a new window and then use jQuery to wait until the new page finishes loading? I attempted the following method, but it was unsuccessful: var win = window.open(url,'',windowSpec); $(win.window).load( function () ...

What is the best method for submitting form data using AJAX?

I am currently facing an issue with submitting a form that I have created using HTML, JS, PHP, and AJAX. Despite my best efforts, the form does not submit as expected. I suspect that the problem lies within my insert function, but I cannot pinpoint exact ...

How can I position an element at the bottom of a page using VueJS and Bootstrap CSS?

https://i.sstatic.net/ojanG.png I am trying to move my footer (Copyright statement) to the bottom of the page. However, it is creating some extra white space beneath the footer. How can I eliminate this additional white space? This issue is occurring in ...

"Encountering a 404 Not Found error while using Next.js and React-Query

I am currently facing a problem with setting up my Next.js project alongside an Express.js back-end. Initially, I set up the back-end as a regular one based on the documentation provided by Next.js. However, I am unsure if this approach is correct. My issu ...

Adjust the background color of the arrow in an HTML Select element

My select menu looks different in Firefox compared to Chrome/Edge In Firefox, it displays an "arrow button" https://i.stack.imgur.com/BGFvO.png However, in Chrome/Edge, the arrow button is not present https://i.stack.imgur.com/PXNJn.png Is there a way ...

Storing information on the webpage when it is refreshed

My goal is to maintain the order of the data in the target ordered list even after a page refresh, achieved through jQuery prepend on document ready. Here's the code snippet: // when a refresh event occurs window.onbeforeunload = function(event){ ...

Bootstrap 4 Carousel Properly Aligned on Small Screens

I am facing an issue with the carousel display. It appears perfectly centered on desktop and laptop screens but shifts to the right on mobile devices. I checked using Chrome developer tools and everything seems aligned correctly within the container. Here ...

jQuery appears to be unresponsive or inactive

I'm trying to implement a jQuery script that will slide in a header after scrolling on the page, but for some reason, it's not working. When I reach the 3rd line, my code editor displays a !read only alert, suggesting there may be a syntax issue? ...

Adjust the size of text using JavaScript to display as an image

Is there a way to adjust the size of a div with text by specifying a width and height so that it fills up the designated area, similar to how an image does when you set its dimensions? I'm looking to take any given width and height values and stretch ...

How to implement a select all feature using React and MaterialUI

I am facing a challenge with managing multiple sets of checkboxes independently along with a toggle that can switch them all on or off within their respective groups. Each checkbox has two states, and I can identify the checkbox being clicked using event.t ...

Is it possible for AngularJS to detect $locationChangeSuccess when the page is refreshed?

In my Angular project, I have set up event listener for $locationChangeSuccess using the following code: $scope.$on('$locationChangeSuccess', function(event) { console.log('Check, 1, 2!'); }); While this works perfectly when navigat ...

Ways to expand flexbox to occupy the entire container

I have a scenario where I want two flexboxes in a container to fill the entire height of the container. The left flexbox should display an image that fills its entire space, while the right flexbox contains other content. However, I'm facing difficult ...

Customizing the styling of an anchor tag using CSS in Bootstrap

I want my active link to appear red: nav class="navbar navbar-inverse"> <div class="container col-1 col-sm-12"> <ul class="nav"> <li class="<%= 'active' if current_page?(squad_path) %> ...

Reset the angular child component trigger by its parent component, which is a modal popup

I'm facing an issue with my Angular application where I have a child component within a parent modal window implemented using ngx-smart-modal. When I close the modal using the method: this.ngxSmartModalService.getModal('ModalNameComponent') ...